E-mails Notification Bot with Python | by Joe T. Santhanavanich | Towards Data Science

In data science, the project’s data sources are probably changing over time, and the analysis result changes quickly over time too. Sometimes a little change in the result might not interest you. But to keep tracking this change by yourself may be too tiresome...
This article shows a guide to scripting the e-mail automation bot with Python!
First, let’s prepare an e-mail sender account. I recommend using G-mail as it is easy to register and allows you to adjust the security option manually. You may use your personal G-mail or other email providers of your choice. But I recommend creating a fresh G-mail for our e-mail bot. 🤖
After the G-mail account is ready, lower the account security to let Python access your G-mail account and send e-mails by going to account security settings and adjusting as follows:
Deactivate the sign-in with the phone
Deactivate the sign-in with a 2-step verification
Turn on the less secure app access option
Now, we arrive at a fun part to write a script to log in to your e-mail account and send an e-mail. I suggest using a simple module smtplib to do this job. First, let’s create a send_email.py file and start with importing modules as follows:
import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMEText
Then, let's prepare all variables for your e-mail sender and recipient's information, and e-mail contents as structured below. You may input several email recipients into the email_recipients list.
#Email Accountemail_sender_account = "<Your Sender Account>"email_sender_username = "<Your Sender Username>"email_sender_password = "<Your Sender Password>"email_smtp_server = "<SMTP, eg smtp.gmail.com for gmail>"email_smtp_port = <SMTP Porf, eg 587 for gmail>#Email Contentemail_recepients = ["<recepient1>","<recepient2>",".."]email_subject = "<Email Subject>"email_body = "<html of your body here>"
After that, we just need to log in to the e-mail server. Then, we will use for loop to generate and send emails to all recipients.
#login to email serverserver = smtplib.SMTP(email_smtp_server,email_smtp_port)server.starttls()server.login(email_sender_username, email_sender_password)#For loop, sending emails to all email recipientsfor recipient in email_receivers:    print(f"Sending email to {recipient}")    message = MIMEMultipart('alternative')    message['From'] = email_sender_account    message['To'] = recipient    message['Subject'] = email_subject    message.attach(MIMEText(email_body, 'html'))    text = message.as_string()    server.sendmail(email_sender_account,recipient,text)#All emails sent, log out.server.quit()
Until here, you have a Python script to send e-mails to all recipients. Now, let’s apply it to the example real-world use case.
In this example, I will show how to apply the Python script we created above to send e-mails to the recipients reporting new COVID-19 cases.
First, we need to get updated COVID-19 data. We can scrape this dataset easily from Worldometers by using BeautifulSoap4 and request modules with a few lines of Python as follows:
#import moduleimport requests, datetimefrom bs4 import BeautifulSoup#Set the endpoint: Worldometersurl = "https://www.worldometers.info/coronavirus/"req = requests.get(url)bsObj = BeautifulSoup(req.text, "html.parser")data = bsObj.find_all("div",class_ = "maincounter-number")num_confirmed = data[0].text.strip().replace(',', '')num_deaths = data[1].text.strip().replace(',', '')num_recovered = data[2].text.strip().replace(',', '')
With this script, it finds the location of a class called maincounter-number which represents the number of COVID-19 data: confirmed cases, deaths, and recovered cases. These data are stored in num_confirmed, num_deaths, num_recovered respectively. Then, we can also get the current time using datetime module and pass these variables to create an HTML structure for the E-mail body as follows:
TimeNow = datetime.datetime.now()email_body = '<html><head></head><body>'email_body += '<style type="text/css"></style>'email_body += f'<h2>Reporting COVID-19 Cases at {time}</h2>'email_body += f'<h1><b>Confirmed cases</b>:  {confirmed_cases}</h1>'email_body += f'<h1><b>Recovered cases</b>:  {recovered_cases}</h1>'email_body += f'<h1><b>Deaths </b>:  {deaths}</h1>'email_body += '<br>Reported By'email_body += '<br>COVID-19 BOT</body></html>'
Now, let’s combine everything together and try if it works by inputting all E-mail info then running python <filename>.py And yes, it works! After running the script, I got an e-mail with a real-time updated COVID-19 case directly to my inbox:
You may take a look at the fully combined Python script below:
Now, it is time to automate your bot to run periodically every xx mins or yy hours or zz days. Also, you should add a condition to send messages because you won’t need 100 reported emails in 10 minutes. So here are what you can do:
Setting a threshold to send an e-mail notification only when new XXXX cases have been reported. A common if..else.. algorithm works well.
Schedule your bot using while true: .../ time.sleep()
Schedule your bot using CRON on your Mac/Linux or using Windows Task Scheduler on Windows.
If you want an alternative way to manage your script to run periodically, I recommend using PM2 to do it.
This article gives a walkthrough to building a Python script for sending emails automatically and periodically with an example of a COVID-19 e-mail notification bot. The e-mail sender used in this tutorial is G-mail but can be replaced with any e-mail provider. The main Python modules of this article include smtplib, request, datetime, bs4 with my main concept to use the easiest way to get to job done. ✌
I hope you enjoyed this article and found it useful for your daily work or projects. Please, feel free to contact me if you have any questions.
About me & Check out all my blog contents: Link
Be Safe and Healthy!Thank you for Reading. 👋😄