I am not very familiar with imaplib, but I am implementing it well with the imapclient module
import imapclient,pyzmail,html2text from backports import ssl context=ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) iobj=imapclient.IMAPClient('outlook.office365.com', ssl=True, ssl_context=context) iobj.login(uname,pwd)# provide your username and password iobj.select_folder('INBOX',readonly=True)# Selecting Inbox. unread=iobj.search('UNSEEN')# Selecting Unread messages, you can add more search criteria here to suit your purpose.'FROM', 'SINCE' etc. print('There are: ',len(unread),' UNREAD emails') for i in unread: mail=iobj.fetch(i,['BODY[]'])#I'm fetching the body of the email here. mcontent=pyzmail.PyzMessage.factory(mail[i][b'BODY[]'])#This returns the email content in HTML format subject=mcontent.get_subject()# You might not need this receiver_name,receiver_email=mcontent.get_address('from') mail_body=html2text.html2text(mcontent.html_part.get_payload().decode(mcontent.html_part.charset))# This returns the email content as text that you can easily relate with.
Say I just want to see unread emails, reply to the sender and mark it as read. I would call the smtp function here to compose and send the answer.
import smtplib smtpobj=smtplib.SMTP('smtp.office365.com',587) smtpobj.starttls() smtpobj.login(uname,pwd)
I hope this helps
Renewble
source share