In this script, we will see how to send email in Python using SMTPLIB library. SMTPLIB is a popular python library which is useful to send email via script.
You do not have to install it, because the library comes by default. In the below python script we use Gmail for the demo, but in your case, you have to use your email server.
Before you understand the script, let’s see what are the details you need to send email in python. Check out the python series for storage admin.
Pre-Requisites To Send Email In Python
In order to script to work you need import the library. As the SMTPLIB library come by default with python, hence, you do not need to install it.
You also need a SMTP server and ports. You can get them for your team who are responsible for managing the exchange servers.
Once you get the SMTP server and port, make sure that the server where your script will run is allowed to send email. Usually a server is allowed to send email if it is added to SMTP relay.
Python Scripts to Send Email
Below is the entire script which sends email in python. You just have to modify the SMTP server and port. Notice that the username and password for the Gmail account are saved in the text file. If you are using the script in your company, then you can remove those lines.
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg[‘Subject’] = ‘Test Mail’
From = “firstname.lastname@example.org”
To = “email@example.com”
Cc = “firstname.lastname@example.org”
text = “Info Collector”
data = “Body content of the mail”
part1 = MIMEText(text, ‘plain’)
part2 = MIMEText(data, ‘plain’)
gmail_cred = open(“gmail_cred.txt”,”r”).read().split(“,”)
s.sendmail(From, To ,msg.as_string())
If you need more details on the script, then watch the below YouTube video. This video is part of series which explains python scripting for Storage Admin.