Send Mail from your Gmail address using Python
Howdy Ho!
Yet another sleepy evening and I find myself almost dozing off. Quick! I need something simple but not boring to do!
That’s right, we’ll try to send an email from our Gmail address using Python!
As always, I love making assumptions. I am going to go on ahead and assume that you have Python installed and know how to run Python programs.
The first thing is to create a new project folder of course.
Gmail uses the SMTP protocol to send mail so we’ll need to get the SMTP library for python. We do that by running:
$pip install smtplib
Once it finishes installing, we can continue.
We begin by importing the smtp library, defining the source and destination addresses, then we define our mail in a json
source = 'user1@gmail.com'
dest = 'user2@gmail.com'
word = "\r\n".join([
"source: user1@gmail.com",
"To: user2@gmail.com",
"Subject: Buenas dias",
"",
"Yo soy Pato"
])
Then we proceed to write the code that sends the email
user = 'user1@gmail.com'
passw = 'xxxxxxx'
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(user,passw)
server.sendmail(source, dest, word)
server.quit()
The whole code:
That’s it! Go to your destination and check, you should find a new email.
All code in this article is available on this Github repo.
Enjoyed the article, find this and more articles on MindNinja. Claps are highly appreciated.