python - 使用 Unicode 发送 HTML 邮件

标签 python python-2.7 email unicode

我修改了 python 文档中的示例,以测试电子邮件模块中的 unicode。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals, print_function

import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# me == my email address
# you == recipient's email address
me = "my@email.com"
you = "your@email.com"

umlauts='German Umlauts: üöä ÜÖÄ ß'

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = umlauts
msg['From'] = me
msg['To'] = you

# Create the body of the message (a plain-text and an HTML version).
text = umlauts
html = """\
<html>
  <head></head>
  <body>
    <p>Hi!<br>
       %s
    </p>
  </body>
</html>
""" % umlauts

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)

# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()

来源:https://docs.python.org/2/library/email-examples.html#id4

我得到这个异常:

user@pc:~$ python src/sendhtmlmail.py 
Traceback (most recent call last):
  File "src/sendhtmlmail.py", line 37, in <module>
    part1 = MIMEText(text, 'plain')
  File "/usr/lib/python2.7/email/mime/text.py", line 30, in __init__
    self.set_payload(_text, _charset)
  File "/usr/lib/python2.7/email/message.py", line 226, in set_payload
    self.set_charset(charset)
  File "/usr/lib/python2.7/email/message.py", line 262, in set_charset
    self._payload = self._payload.encode(charset.output_charset)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 16-18: ordinal not in range(128)

发送text+html邮件如何处理unicode?

最佳答案

您需要将其显式编码为 UTF-8。

part1 = MIMEText(text.encode('utf-8'), 'plain', 'utf-8')
part2 = MIMEText(html.encode('utf-8'), 'html', 'utf-8')

或者,避免导入 unicode_literals,您的字符串将首先是字节。

关于python - 使用 Unicode 发送 HTML 邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36397827/

相关文章:

Python 电子邮件机器人 Pyzmail/IMAPclient 错误

python - 遍历类中所有像枚举一样的变量

Python smtplib 破坏 html 电子邮件

python - Cython 中的 C++ 指针

python - 没有 MousePress 的 PyQt4 MouseMove 事件

Python 2.7.6 将单个 "high"unicode 代码点一分为二

python - 在所有行中附加多个 CSV 以及每个 CSV 的名称 - Python

php - 在 Laravel 5 中将文件附加到电子邮件

php - 如何为 PHP 应用程序设置水滴电子邮件系统

python - 如何获取桌面位置?