发送附件列表/数组的电子邮件,仅发送给列表中的最后一个人

时间:2017-01-12 11:55:05

标签: python openpyxl smtplib

电子邮件将发送给不符合if中设置条件的最后一个人。

我无法理解为什么它不会将电子邮件发送给符合条件的文件中的其他人。

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()

1 个答案:

答案 0 :(得分:0)

email设置为for循环中的最后一个值,这就是为什么它只是将电子邮件发送给最后一个人。

您应该做的是创建收件人列表,然后使用该信息:

...
...
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)

按照此SO帖子中的答案获取更多详细信息:How to send email to multiple recipients using python smtplib?