I need to write a program that checks a gmail inbox using imaplib
and forwards out emails that do not match a specific subject to a separate email. I can do this using stmplib
but I do not know how to do it if the email that needs to be forwarded out and deleted contains an attachment. The following is my code that I need to update to be able to handle emails with attachments.
# Connect and login to email
imap = imaplib.IMAP4_SSL('imap.gmail.com')
imap.login('user@gmail.com','password')
imap.list()
imap.select('inbox')
smtp = smtplib.SMTP_SSL('smtp.gmail.com')
smtp.login('user@gmail.com','password')
try:
#Search and return sequential ids
result, data = imap.search(None,'ALL')
ids_list = data[0].split()
#print 'Total emails: '+str(len(ids_list))
latest_id = ids_list[-1]
#Process each email in inbox
for i in ids_list:
t, d = imap.fetch(i, '(RFC822)')
for res_part in d:
if isinstance(res_part, tuple):
text = res_part[1]
msg = email.message_from_string(text)
subject = msg['subject']
#print 'Subject: '+subject
message = get_txt(msg) #Retrieves email body text
#print message
if subject != 'The subject I\'m looking for': #Junk email
#print 'Sending to another email...'
smtp.sendmail('from@gmail.com', 'to@email.com', message)
imap.store(i, '+FLAGS', '\\Deleted')
imap.expunge()
else: #Email we need to process
#print 'Process this email'
except IndexError:
#Inbox is empty
Can somebody show me the proper way to accomplish this? Thanks!
To use this library you need an working SMTP server. You can use the one of you email provider, or you can setup one for yourself.
After this is done you cannot as a link, as example for an FTP server, on which you file is laying. This should also be supported with POP.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.