E-mails through Python!
Sending e-mails using Python. Yes, you read it right.
This article is going to revolve around how one can send e-mails through Gmail using Python using the SMTP and e-mail libraries. The methodology is pretty straightforward and easy to follow. So without any further ado, let’s begin!
Before you begin writing the code, you will need to make certain security changes to the Gmail account you intend to use for this little demonstration. All you need to do is go to ‘Manage Your Google Account’ and in there, go to the security settings. Once you are there, all you need to do is turn on the ‘Less Secure App Access’.
Now, we can start writing the code.
For this, you only require two libraries: SMTP and MIMEText from email library.
SMTP or the ‘Simple Mail Transfer Protocol’ which essentially handles the sending and routing of emails between servers. Python generously provides us with an in-built smtplib module through which we can create an SMTP client session object which can be used to send emails.
MIMEText from the email library will be used to construct the email, that is, the body and the subject.
The code looks like this.
import smtplib
from email.mime.text import MIMETexts = smtplib.SMTP('smtp.gmail.com', 587) #creates objects.starttls()s.login('sender_email@gmail.com', 'password')message = MIMEText('Hey') #Body of the email
message['Subject'] = 'Hi!' #Subject of the email
list = ['receiver_address_1@gmail.com', 'receiver_address_2@gmail.com'] #the list of all the destinationsfor i in list:
s.sendmail('sender_email@gmail.com', i, message.as_string())s.quit()
You could even read a file into a string and save that to the message as the body of the mail.
For simplicity, I sent myself a mail using this, and the output you get after you run the program is something like this.
This little snippet of code could be a nice little weapon in your arsenal. You could use it to e-mail your output directly. You could even use it as an alert system and use it send alerts directly to your inbox. This is a pretty versatile piece of code and could take your program up a notch.
I hope you liked this short article and please stay tuned for future projects.