【问题标题】:Send email with sender and recipient header in python在 python 中发送带有发件人和收件人标头的电子邮件
【发布时间】:2018-05-01 14:31:13
【问题描述】:

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。如何添加发件人标头字段,以便将发件人显示为Someone important (creditcards@domain.in)

【问题讨论】:

    标签: python email smtplib


    【解决方案1】:

    我使用来自email.headerHeader 和来自email.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() 
    

    【讨论】:

    • 从 Python 3.6 开始,email.headeremail.utils 大部分是不推荐使用的模块。当前的解决方案是使用email.headerregistry 模块中的Address 类:msg['From'] = Address('Finance Manager', 'creditcards', 'domain.in')
    猜你喜欢
    • 2022-12-17
    • 2019-06-17
    • 2015-08-29
    • 2019-05-04
    • 2013-03-03
    • 2014-04-02
    • 2021-07-19
    • 2012-05-18
    相关资源
    最近更新 更多