gpt4 book ai didi

python - 邮件会发送 3 次,而不是每个地址一次?

转载 作者:行者123 更新时间:2023-11-30 22:44:02 24 4
gpt4 key购买 nike

我想出了一些对我来说似乎很奇怪的东西,并且我不确定到底要搜索什么。

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

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)

fromaddr = "xxxx@xxxx.com"

for n in recipients:
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = n
msg['Subject'] = "Hi"

body = "This is a test mail"

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

filename = "xxx.pdf"
attachment = open("\\Users\xxx\xxx\xxx.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, 'xxxxx')
text = msg.as_string()
smtp0bj.sendmail(fromaddr, recipients, text)
smtp0bj.quit()

我猜测 for 循环被执行了 3 次(列表中有 3 项。我不知道如何让它只执行一次。

最佳答案

你基本上就是这么做的:

for n in recipients: # for each recipient
smtp0bj.sendmail(fromaddr, recipients, text) # send mail to all recipients

因此,每次传递时,它都会将邮件发送给所有收件人。

因此,如果您有 3 个收件人,他们将每人收到 3 封邮件。

替换为:

smtp0bj.sendmail(fromaddr, n, text)

我也不确定,现在无法测试,但我相信“to”必须是一个列表。因此,如果上述解决方案不起作用,请尝试一下:

smtp0bj.sendmail(fromaddr, [n], text)

关于python - 邮件会发送 3 次,而不是每个地址一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41620346/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com