import smtplib import time import imaplib import email from os.path import basename from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import COMMASPACE, formatdate class User: def __init__(self, login, password, imap='imap.gmail.com', smtp='smtp.gmail.com:587'): self.imap = imaplib.IMAP4_SSL(imap) self.imap.login(login, password) self.smtp = smtplib.SMTP(smtp) self.smtp.starttls() self.smtp.login(login, password) def read(self, search='ALL', action='', advancedSearch=None): #delete #0: keep, 1: move to trash, 2: delete text = [] raw = [] self.imap.list() # Lists all labels in GMail self.imap.select('inbox') # Connected to inbox. result, data = self.imap.uid('search', None, search) # search and return uids instead i = len(data[0].split()) # data[0] is a space separate string for x in range(i): latest_email_uid = data[0].split()[x] # unique ids wrt label selected result, email_data = self.imap.uid('fetch', latest_email_uid, '(RFC822)') # fetch the email body (RFC822) for the given ID raw_email = email_data[0][1] #continue inside the same for loop as above raw_email_string = raw_email.decode('utf-8') # converts byte literal to string removing b'' email_message = email.message_from_string(raw_email_string) # user defined search if advancedSearch != None: if not advancedSearch(imapserver=self.imap, uid=latest_email_uid, msg=email_message): continue # raw.append(email_message) # this will loop through all the available multiparts in mail for part in email_message.walk(): if part.get_content_type() == "text/plain": # ignore attachments/html body = part.get_payload(decode=True) text.append(body.decode('utf-8')) if action: if action == 'TRASH': self.imap.uid('COPY', latest_email_uid, '[Gmail]/Trash') elif action == 'DELETE': self.imap.uid('STORE', latest_email_uid, '+FLAGS', '(\Deleted)') else: self.imap.uid('STORE', latest_email_uid, '+FLAGS', action) self.imap.expunge() return {'text': text, 'raw': raw, 'uid': data[0].split()} def send(self, send_from, send_to, subject, text, files=[]): msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) for f in files or []: with open(f, "rb") as fil: part = MIMEApplication( fil.read(), Name=basename(f) ) # After the file is closed part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f) msg.attach(part) self.smtp.sendmail(send_from, send_to, msg.as_string()) def close(self): self.imap.close() self.imap.logout() self.smtp.quit()