Sending Bulk Emails With Python
An automated way to send out your emails
Sending emails manually is a tedious, time-consuming, and error-prone task. We can automate this process using Python.
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.