python - 如何向国际地址发送电子邮件

标签 python python-2.7 email unicode

如何通过 smtplib 向国际地址发送电子邮件在Python 中?

如果我使用以下代码

    try:
        server = None

        msg = MIMEMultipart('alternative')
        msg['From'] = formataddr((from_email_name, from_email))
        msg['To'] = Header(to_email, 'utf-8')
        msg['Subject'] = Header(subject, 'utf-8')

        plain_text_part = MIMEText(plain_text_body, 'plain', _charset='utf-8')
        msg.attach(plain_text_part)

        html_part = MIMEText(html_body, 'html', _charset='utf-8')
        msg.attach(html_part)

        server = smtplib.SMTP(smtp_server)
        server.starttls()
        server.login(from_email, from_email_password)
        server.sendmail(from_email, to_email, msg.as_string())
    finally:
        if server is not None:
            server.quit()

然后,当我使用 ñoñó<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdfcfffef98dbea8bfbba8bfe3aea2a0" rel="noreferrer noopener nofollow">[email protected]</a> 调用此代码时,脚本在下一行失败电子邮件作为目标地址 (to_email):

server.sendmail(from_email, to_email, msg.as_string())

输出

'ascii' codec can't encode character u'\xf1' in position 9: ordinal not in range(128)

但是如果我更改 sendmail函数调用如下

server.sendmail(from_email, to_email.encode('utf-8'), msg.as_string())

它失败并出现以下错误:

{'\xc3\xb1o\xc3\xb1\xc3\[email protected]': (555, '5.5.2 Syntax error. i7sm368361lbo.39 - gsmtp')}

我正在使用 GMail 的 SMTP 服务器发送这些电子邮件。

如何修复它?

提前致谢。

最佳答案

RFC 6533 - Overview and Framework for Internationalized Email 指出服务器端:

An SMTP relay MUST

  • Either recognize the format explicitly, agreeing to do so via an ESMTP option, or
  • Reject the message or, if necessary, return a non-delivery notification message, so that the sender can make another plan.

还有 RFC 6531 - SMTP Extension for Internationalized Email 表示为精度(摘录):

  • The EHLO keyword value associated with this extension is "SMTPUTF8"
  • One OPTIONAL parameter, SMTPUTF8, is added to the MAIL command.
  • If the envelope or message being sent requires the capabilities of the SMTPUTF8 extension, the SMTPUTF8-aware SMTP client MUST supply the SMTPUTF8 parameter with the MAIL command.

由于与 GMail SMTP 服务器的交换痕迹证明它声明自己是 SMTPUTF8 兼容服务器,因此您只需要求 smtplib 提供 SMTPUTF8 选项即可邮件命令。您只需将sendmail命令更改为:

server.sendmail(from_email, to_email.encode('utf-8'), msg.as_string(), ['SMTPUTF8'])

由于您已经处理了正文中最终的非 ASCII 字符,并使用 MIMEMultipart 和 MIMEText 设置了适当的 header ,所以一切都应该没问题。

关于python - 如何向国际地址发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34040613/

相关文章:

python - 为什么使用 range() 来单独让索引和元素同时可用是不好的?

php - 将弹出窗口 'email has been sent' 更改为 Bootstrap 'contextual background'?

email - 电子邮件地址中是否应该允许使用大写字母?

python 2.7 : How to convert unicode escapes in a string into actual utf-8 characters

python - 遍历链表的函数

python-2.7 - Pandas 0.18.1 groupby 和重采样多级聚合错误

email - 如何从您的应用程序发送干净的电子邮件?

python - Python 中 4D 向量的可视化

python - 在 TCP Python SocketServer 中捕获目标 IP

python - 无序集合 - 在 python 中设置