html 使用python发送个性化电子邮件

cbwuti44  于 2022-12-28  发布在  Python
关注(0)|答案(1)|浏览(89)

我是一个初学者,尝试用python发送个性化的电子邮件。

import smtplib, ssl

def read_creds():
    user = passw = ""
    with open("credentials.txt", "r") as f:
        file = f.readlines()
        user = file[0].strip()
        passw = file[1].strip()

    return user, passw

port = 465

sender, password = read_creds()

receive = sender

message = """\
Subject: Python

This is from python!
"""

context = ssl.create_default_context()

print("Starting to send")
with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
    server.login(sender, password)
    server.sendmail(sender, receive, message)

print("email sent.")

我想在每封邮件中添加一个个性化代码(例如,可以是123456),但从我读过的教程中我不明白如何操作。

aydmsdu9

aydmsdu91#

您需要确定从文件或数据库检索联系人列表的方法,为了简单起见,我将使用数组。
首先更新您的消息以支持自定义消息:

message = """
Subject: Message subject

Hi {name}, you have got a personal message!
"""

然后更新发送电子邮件背后的逻辑,并将收件人添加到数组中(在真实的生活中使用数据库或文件):

recipients = [{"email":"email1@aol.com", "name":"Misha"},{"email":"email2@aol.com", "name":"Andrey"}]

print("Starting to send")
with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
    server.login(sender, password)
    for recipient in recipients:
        server.sendmail(sender, recipient["email"], message.format(name=name))

相关问题