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 ='
>>> to_address  = ''
>>> subject = 'Email testing'
>>> body = 'Just a test...'
>>> message = 'Subject: {}\n\n{}'.format(subject, body)
>>> username = ''
>>> password = 'my_plaintext_password'
>>> server = smtplib.SMTP('')
>>> server.ehlo()
>>> server.starttls()
(220, '2.0.0 Ready to start TLS')
>>> server.login(username,password)
(235, '2.7.0 Accepted')
>>> server.sendmail("", 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 *