Work Automation – Bulk email send out via Python (Gmail Servers)

This project has been done before on this site, the only difference here is we’ll be making use of Gmail servers to send our bulk instead.

Before we start ensure that you have a list of recipients saved to an xlsx file containing the names and email addresses of our recipients.

we begin by opening the Excel spreadsheet via Openpyxl and define the sheet name. With the sheet now open we will iterate through all entries and define the name and email data. With each set of data we make a call to the sendEmail function which sends the email.

def Main():
    wb = openpyxl.load_workbook('C:\Desktop\Spreadsheet.xlsx')
    sheet = wb["Sheet1"]
    for i in range(2,sheet.max_row+1):
        Name = str(sheet.cell(row = i, column = 1).value)
        Email = str(sheet.cell(row = i, column = 2).value)
        sendEmail(Name,Email)
       

The emails are sent via a mail server, if you do not have one of these you could always resort to using a third party mailing server i.e. Gmail. I am hoping to cover this in the next post. We would also define the contents of the email in this function which is a plain text mail.

def sendEmail(Name,Email):
    fromx = FromAddress
    to = Email
    msg = MIMEText('Hello, How are you?')
    msg['Subject'] = 'Some subject'
    msg['From'] = fromx
    msg['To'] = Email
    server = smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.ehlo()
    server.login(FromAddress,Password)
    server.sendmail(fromx, to, msg.as_string())
    server.quit()
    

The source code in full can be found below:

from openpyxl import Workbook
import openpyxl
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def sendEmail(Name,Email):
    fromx = FromAddress
    to = Email
    msg = MIMEText('Hello, How are you?')
    msg['Subject'] = 'Some subject'
    msg['From'] = fromx
    msg['To'] = Email
    server = smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.ehlo()
    server.login(FromAddress,Password)
    server.sendmail(fromx, to, msg.as_string())
    server.quit()
    
def Main():
    wb = openpyxl.load_workbook('C:\Desktop\Spreadsheet.xlsx')
    sheet = wb["Sheet1"]
    for i in range(2,sheet.max_row+1):
        Name = str(sheet.cell(row = i, column = 1).value)
        Email = str(sheet.cell(row = i, column = 2).value)
        sendEmail(Name,Email)

def Main()

Leave a Reply