0

The email is being sent to the last person who doesn't meet the criteria set in the if.

I can't understand why it wont send the email to others in the file which meet the criteria.

import smtplib, openpyxl, sys from email.mime.multipart 
import MIMEMultipart from email.mime.text 
import MIMEText from email.mime.base 
import MIMEBase from email 
import encoders    
wb = openpyxl.load_workbook('Book1.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')    

lastCol = sheet.max_column  
latestMonth = sheet.cell(row=1, column=lastCol).value

unpaidMembers = {}   
for r in range(2, sheet.max_row + 1):
    payment = sheet.cell(row=r, column=lastCol).value
    if payment != 'Y':
        name = sheet.cell(row=r, column=1).value
        email = sheet.cell(row=r, column=2).value
        unpaidMembers[name] = email

fromaddr = "xxx@xxxx.com"

msg = MIMEMultipart()

msg['From'] = fromaddr
msg['To'] = email
msg['Subject'] = "Hi"

body = "Hello, This is a test message. Please check attachment"

msg.attach(MIMEText(body, 'plain'))

filename = "xxxxx.pdf"
attachment = open("\\\xxxx.pdf","rb")

part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" %  filename)

msg.attach(part)

smtp0bj = smtplib.SMTP('smtp-mail.outlook.com', 587)
smtp0bj.ehlo()
smtp0bj.starttls()
smtp0bj.login(fromaddr, 'xxxx')
text = msg.as_string()
smtp0bj.sendmail(fromaddr, email, text)
smtp0bj.quit()
hennamusick
  • 267
  • 1
  • 3
  • 17
Sid
  • 3,749
  • 7
  • 29
  • 62

1 Answers1

0

email is set to the last value in the for loop and that's why it is only sending the email to last person.

What you should do is create a list of recipients and then use that information:

...
...
recipients = []
unpaidMembers = {}   
for r in range(2, sheet.max_row + 1):
    payment = sheet.cell(row=r, column=lastCol).value
    if payment != 'Y':
        name = sheet.cell(row=r, column=1).value
        email = sheet.cell(row=r, column=2).value
        unpaidMembers[name] = email
        recipients.append(email) 

...
...
msg["To"] = ", ".join(recipients)
...
...
smtp0bj.sendmail(fromaddr, recipients, text)

Follow the answers in this SO post for more details: How to send email to multiple recipients using python smtplib?

Community
  • 1
  • 1
AKS
  • 18,983
  • 3
  • 43
  • 54
  • Thanks. That worked perfectly. However, I don't want to send the mail at once to everyone but one recipient at a time. i.e. one mail per recipient. I will read the thread you have posted. – Sid Jan 12 '17 at 12:26