import smtplib
To connect to SMTP server of your provider
conn = smtplib.SMTP('smtp.gmail.com', 587)
type(conn)
conn
Next, call ehlo()
conn.ehlo()
Call starttls()
to start TLS encryption
conn.starttls()
Call login()
with your username and password
conn.login('vrunrun@gmail.com','egliztzoghkrtbvw')
Call sendmail()
with the "from", "to" email addresses, the subject line followed by the message body. The returned object contains email address that are failed to send.
conn.sendmail('vrunrun@gmail.com', 'vrunrun@gmail.com', 'Subject: So long...\n\nDear X,\nSo long, and thanks for all the fish\n\n-XX')
Call quit()
to close the connection
conn.quit()
The returned tuple from conn.ehlo()
, conn.starttls()
, conn.login()
consists of a digit and a string of bytes data type. For the digit, anything starts with 2 means OK. All bytes data begin with a "b"
Provider | SMTP server domain name |
---|---|
Gmail | smtp.gmail.com |
Outlook.com/Hotmail.com | smtp-mail.outlook.com |
Yahoo Mail | smtp.mail.yahoo.com |
AT&T | smtp.mail.att.net (port 465) |
Comcast | smtp.comcast.net |
Verizon | smtp.verizon.net (port 465) |
Google has something called app specific password that gives an app permission to access your Google Account. You should pass app specific password to conn.login()
method instead of password for normal google account
Email providers impose limit on number of emails send per day
The Internet Message Access Protocol (IMAP) specifies how to communicate with email server to retrieve emails.
# pip install imapclient
# pip install pyzmail36 (for Python 3.6.x)
# pip install pyzmail (for older Python version)
import imapclient
conn = imapclient.IMAPClient('imap.gmail.com', ssl=True)
conn.login('vrunrun@gmail.com','egliztzoghkrtbvw')
conn.select_folder('INBOX', readonly=True)
UIDs = conn.search('(SINCE "6-Mar-2018")')
UIDs
rawMessage = conn.fetch([2873], ['BODY[]', 'FLAGS'])
import pyzmail
pyzmail.PyzMessage.factory(rawMessage[2873][b'BODY[]'])
message = pyzmail.PyzMessage.factory(rawMessage[2873][b'BODY[]'])
message.get_subject()
message.get_addresses('from')
message.get_addresses('bcc')
message.text_part
message.text_part == None
message.text_part.get_payload().decode('UTF-8')
message.text_part.charset == None
conn.list_folders()
Delete emails
conn.select_folder('INBOX', readonly=False)
UIDs = conn.search('(ON "7-Mar-2018")')
UIDs
# conn.delete_messages([2867])
# conn.delete_messages(UIDs)
conn.logout()
Provider | IMAP server domain name |
---|---|
Gmail | imap.gmail.com |
Outlook.com/Hotmail.com | imap-mail.outlook.com |
Yahoo Mail | imap.mail.yahoo.com |
AT&T | imap.mail.att.net |
Comcast | imap.comcast.net |
Verizon | imap.verizon.net |
Refer to table 16-3 of the <a href = "https://automatetheboringstuff.com/chapter16/" target="_blank">"Automate the Boring Stuff with Python"</a> book
See the IMAP cheat sheet in the course notes for an overview of the entire process
More documentation at: https://imapclient.readthedocs.org http://www.magiksys.net/pyzmail