Sending Email with Python

This post is a simple example of sending email with Python. I’ve been using Python recently to run various scripts, and email me the results of the script. Also, it’s nice to craft your own emails, even though the big email vendors sometimes rewrite the headers.

This is a simple example using the Python (3.5.1) interpreter and Gmail:

>>> import smtplib
>>> from_address = address_that_appears_on_the_from_line@gmail.com'
>>> to_address  = 'the_recipient@someone.com'
>>> subject = 'Email testing'
>>> body = 'Just a test...'
>>> message = 'Subject: {}\n\n{}'.format(subject, body)
>>> username = 'my_email_address@gmail.com'
>>> password = 'my_plaintext_password'
>>> server = smtplib.SMTP('smtp.gmail.com:587')
>>> server.ehlo()
(250, 'smtp.gmail.com at your service, [68.203.193.38]\nSIZE 35882577\n8BITMIME\nSTARTTLS\nENHANCEDSTATUSCODES\nPIPELINING\nCHUNKING\nSMTPUTF8')
>>> server.starttls()
(220, '2.0.0 Ready to start TLS')
>>> server.login(username,password)
(235, '2.7.0 Accepted')
>>> server.sendmail("address_I_could_spoof_or_not@example.com", to_address, message)
{}

The first argument in server.sendmail should be the originating email address, but you can put whichever email you want. It is essentially the reply-to email address, (sometimes called the bounce address), but it will likely get re-written by the sending SMTP server.

Leave a Reply

Your email address will not be published. Required fields are marked *