![](/img/trans.png)
[英]What's wrong with my Python attempt at sending mail via SMTP through Gmail? The SSL wrapper doesn't seem to work
[英]Python: sending mail with SMTP (to Gmail) and can't encode headers properly
我有以下代码片段,部分是从stackoverflow用户那里借来的:
#!/usr/bin/env python
# -*- coding: iso-8859-2 -*-
def send_email(user, pwd, recipient, subject, body):
import smtplib
FROM = user
TO = recipient if type(recipient) is list else [recipient]
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """From: %s\nTo: %s\nSubject: =?iso-8859-2?Q?%s?=\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
print(message)
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(user, pwd)
server.sendmail(FROM, TO, message)
server.close()
print('successfully sent the mail')
except:
print("failed to send mail")
sentence='Koń'
send_email('login','pass','recipient@gmail.com',sentence.encode('iso-8859-2'),'test')
它将电子邮件从一个gmail帐户发送到另一个gmail帐户,但是当我登录到gmail页面时,主题显示为
b'Ko\xf1'
我究竟做错了什么?
推荐的解决方案:使用email.header中的 Header
功能
说明: RFC-2047期望在=?iso-8859-2?Q?...?=
内加引号的可打印编码字符串。
您输入“原始”字符串。
koń
有效utf-8编码编码为Subject: =?UTF-8?Q?ko=C5=84?=
建议: 如果可以,请考虑使用utf-8
而不是iso-8859-2
。 对于“几乎为ascii”的语言, utf-8
更为通用(较少区域性),而资源成本(例如磁盘空间)则很少。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.