使用Unicode发送HTML邮件 [英] Send HTML Mail with Unicode
本文介绍了使用Unicode发送HTML邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我修改了python文档中的示例,以在电子邮件模块中测试unicode。
I modified the example from the python docs, to test unicode in the email module.
#!/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)
如何处理Unicode是否要发送文本+ html邮件?
How to handle unicode if you want to send a text+html mail?
推荐答案
您需要将其明确编码为UTF-8。
You'll need to explicitly encode it to UTF-8.
part1 = MIMEText(text.encode('utf-8'), 'plain', 'utf-8')
part2 = MIMEText(html.encode('utf-8'), 'html', 'utf-8')
或者,避免导入unicode_literals,而您的字符串将首先是字节。
Or, avoid importing unicode_literals, and your strings will be bytes in the first place.
这篇关于使用Unicode发送HTML邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文