在 python 中发送发件人和收件人 header 的电子邮件

Send email with sender and recipient header in python

failing 使用 Mailgun API 发送电子邮件后,我一直在使用 smtplib 使用 SMTP 成功发送电子邮件,代码如下。

def send_simple_message(mailtext, mailhtml):
    print("Mailhtml is:" + mailhtml)
    logging.basicConfig(level=logging.DEBUG)
    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "Summary of Credit Card payments due"
    msg['From']    = "creditcards@domain.in"
    msg['To']      = "me@domain.in"
    s = smtplib.SMTP('smtp.mailgun.org', 587)
    part1 = MIMEText(mailtext, 'plain')
    part2 = MIMEText(mailhtml, 'html')
    msg.attach(part1)
    msg.attach(part2)
    s.login('postmaster@domain.in', 'password')
    s.sendmail(msg['From'], msg['To'], msg.as_string())
    s.quit()

然而,这会将发件人字段显示为 creditcards@domain.in。如何添加发件人 header 字段,以便发件人显示为 Someone important (creditcards@domain.in)

我用 email.headerHeaderemail.utilsformataddr 解决了这个问题。我的完整工作脚本如下所示:

def send_simple_message(mailtext, mailhtml, month, files=None):
    # print("file is:" + filename)
    logging.basicConfig(level=logging.DEBUG)
    import smtplib
    from os.path import basename
    from email.mime.application import MIMEApplication
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from email.header import Header
    from email.utils import formataddr
    Recipient = "me@domain.com"
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "Summary of Credit Card payments due in " + month
    msg['From'] = formataddr((str(Header('Finance Manager', 'utf-8')), 'creditcards@domain.in'))
    msg['To']      = Recipient
    part1 = MIMEText(mailtext, 'plain')
    part2 = MIMEText(mailhtml, 'html')
    msg.attach(part1)
    msg.attach(part2)
    for f in files or []:
        with open(f, "rb") as fil:
            part = MIMEApplication(
                fil.read(),
                Name=basename(f)
            )
        # After the file is closed
        part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
        msg.attach(part)

    s = smtplib.SMTP('smtp.mailgun.org', 587)
    s.login('postmaster@domain.in', 'pass')
    s.sendmail(msg['From'], msg['To'], msg.as_string())
    s.quit()