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 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)
Below is the sendEmail function which uses the name and email data as seen above. Using the Gmail server we are able to send emails by using our own account credentials,
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()