在 Python 的自动电子邮件脚本中自定义收件人姓名时出错

Error in customizing receiver's name in automated email script in Python

我尝试编写一个自动将电子邮件发送到电子邮件地址列表的脚本,并希望使用格式化程序自定义正文内容,如下所示:

<html>
Hello {name}, it is me
</html>

所以我写了下面的脚本参考 并且没有问题将电子邮件发送给每个收件人 - 但问题是电子邮件正文内容随着收件人数量的增加而累积。例如,列表中的第 4 个收件人最终收到一封包含 4 个正文内容的电子邮件,是第 1、第 2 和第 3 个收件人电子邮件内容的总和。为什么会发生这种情况,我该如何解决?

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import time
import random

fromaddr = "sender_gmail_account"

msg = MIMEMultipart()
msg['From'] = fromaddr
msg['Subject'] = "Subject_line"

#list of receivers
s = open("list.txt", "r")
emails = s.readlines()
print emails
s.close()

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "gmail_password")

for address in emails:
    address = address.strip().split(",")      # Removing White spaces.
    toname = address[0]
    toaddr = address[1].strip()
    if toaddr == "":
        continue

    f = open('mail_template.html')
    body = f.read()
    f.close()

    msg['To'] = toaddr
    body = body.format(name=toname)

    msg.attach(MIMEText(body, 'html'))
    text = msg.as_string()
    body = ""
    server.sendmail(fromaddr, toaddr, text)

    rand = random.randrange(2,5)       # Set range of the waiting time.
    time.sleep(rand)

server.quit()

yagmail 非常适合编写 html 电子邮件(本质上,所有电子邮件都是 html 带有简单文本的电子邮件,作为无法处理 html 的浏览器的替代) .请注意,yagmail 还将使登录变得容易,等等。

import yagmail
import random
import time

yag = yagmail.SMTP(fromaddr, 'gmail_password')

template = 'Hello {name}, it is me'           # yagmail automatically makes this HTML
# template = '<h1>Now with big header</h1>'   # other template example     

for address in addresses:
    address = address.strip().split(",")      # Removing White spaces.
    toname = address[0]
    toaddr = address[1].strip()
    if toaddr == "":
        continue

    yag.send(address, "Subject_line", template.format(name=toname))

    time.sleep(random.randrange(2,5))

使用以下方式获取 yagmail:

pip install yagmail

从 48 行增加到 19 行:不错 ;)

完全披露:我是 yagmail 的开发者。