Sending an Email Using Python
By Kalyani Rajalingham, published 15/10/2020 in Tutorials
Ever wanted to send emails using just Python? A few lines of code and you don’t even need to log into your Gmail account to email anyone in the world. In fact, you can do this in your terminal.
First, open up your terminal and create a file. I will call mine “emailer.py”.
nano emailer.py
Now, let’s add some code to the file we just created. In the first instance, we will need to import smtplib.
Import smtplib
Next, let’s define the server and the port of the email service we use. In my case, since I use Gmail, the server and port will be that of Gmail’s. However, if you use a service other than Gmail, you can simply Google the server address.
server = “smtp.gmail.com”
port = 587
smtp = smtplib.SMTP(server, port)
Let’s initiate a secure connection.
smtp.ehlo()
smtp.starttls()
We now need a valid Gmail account (both username and password) to log into. In my case, I created a dummy account just for this. Please note that your Gmail account’s setting must be such that the “less secure apps” (manage your Gmail account >> Security >> Less secure apps access) are on.
user= “videosys262@gmail.com”
password= “Password1.”
smtp.login(user, password)
To define the content that I will be sending:
content = “This email was sent using Python code only”
And finally, to send the message, we use sendmail(from, to, message).
smtp.sendmail(user, user, content)
The entire code would look something like this:
Import smtplib
server = “smtp.gmail.com”
port = 587
smtp = smtplib.SMTP(server, port)
smtp.ehlo()
smtp.starttls()
user= “videosys262@gmail.com”
password= “Password1.”
smtp.login(user, password)
content = “This email was sent using Python code only”
smtp.sendmail(user, user, content)
Once you’ve written the code, the next step is to run it:
python emailer.py
Easy, breezy, beautiful code to send an email.