将带附件的电子邮件发送给 list/array,仅发送给列表中的最后一个人

Send email with attachment to a list/array, only getting sent to last person in the list

正在将电子邮件发送给不符合 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()

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 post 中的答案了解更多详细信息:How to send email to multiple recipients using python smtplib?