Sending Bulk Emails With Python

An automated way to send out your emails

Sarath Kaul
Level Up Coding

--

Sending emails manually is a tedious, time-consuming, and error-prone task. We can automate this process using Python.

Getting Started

Python comes with various inbuilt modules. One that we can use for sending mails is smptlib, which uses the Simple Mail Transfer Protocol (SMTP). The code that we write will use the Gmail SMTP server to send emails using Port 587 or 465.

Sending Plain-Text Emails

We will start by importing all the helper modules that are required to send out emails.

We will use email.mime to structure our email message.

We need to specify the email account and its credentials, which will be used to send out emails.

Now, the core part will include the list of receiving emails and various headers of our email, like Subject, Body.

In this case, we will send a simple text message.

# list of users to whom email is to be sent
email_send = ['LIST_OF_RECIPIENTS']
subject = 'EMAIL_SUBJECT'msg = MIMEMultipart()
msg['From'] = email_user
# converting list of recipients into comma separated string
msg['To'] = ", ".join(email_send)
msg['Subject'] = subjectbody = 'EMAIL_BODY'
msg.attach(MIMEText(body,'plain'))
text = msg.as_string()
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(email_user,email_password)
server.sendmail(email_user,email_send,text)
server.quit()

The above code can be integrated with any front-end screen to receive LIST_OF_RECIPIENTS dynamically to send bulk emails at once.

Sending Emails With HTML Content

There isn’t a lot of change when sending out Emails with HTML content. We just need to tweak our Email Body a little, which will now contain text in the form of HTML.

So we changed our body text to one containing HTML, and MIMEText containing our body will refer it to as html instead of plain.

You can also use the above-described approach to send out emails containing attachments.

More Information/Documentation

--

--

Web Developer | Google Certified ACE | Open Source Fanatic | CS Graduate …. Check out my portfolio on skaul05.netlify.app