Python has some modules in the standard library that help working with emails and email servers.
In this guide we will be using the smtplib module of python. SMPTlib defines an SMTP client session object that is used to email any Internet machine with an SMTP or ESMTP listener daemon.
By the end of this guide, you’ll be able to just send emails using such a simple line of code:
mailman.sendmail(‘SENDER EMAIL’, ‘PASSWORD’, ‘TO EMAIL’, ‘SUBJECT’,’BODY’)
There are 4 basic steps to send email with python, those are:
- Set up the SMTP server and log into your account.
- Create a MIMEMultipart object and add appropriate headers.
- Add message body.
- Send the message using the SMTP server object.
Here’s the sample code:
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def sendmail(from_email, password, to_email, subject, message):
# setup the parameters of the message
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = to_email
msg['Subject'] = subject
# add in the message body
# set up the SMTP server
# host and port, you can leave port empty as 465 is the default anyway
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.sendmail(msg['From'], msg['To'], msg.as_string())
except Exception as e:
print('Something went wrong: ' + str(e))
Now you can call this method wherever you like to send emails like this:
sendmail('SENDER EMAIL', 'PASSWORD', 'TO EMAIL', 'SUBJECT',
There are a lot more things that I’ve not covered here, but I hope this gets you started, if you have any issues sending email from python, feel free to ask about those in the comments section below.