在python中';s smtplib为什么不';主题或字段集?
任何人都能理解为什么以下代码成功发送电子邮件,但它在收件人收件箱中显示为发件人的电子邮件地址,而不是发件人的姓名,并且主题在其收件箱中显示为“无主题”。提前谢谢在python中';s smtplib为什么不';主题或字段集?,python,smtplib,Python,Smtplib,任何人都能理解为什么以下代码成功发送电子邮件,但它在收件人收件箱中显示为发件人的电子邮件地址,而不是发件人的姓名,并且主题在其收件箱中显示为“无主题”。提前谢谢 def send_email(destination, subject, message): from_who = "My Name" to_send = """\From: %s\nTo: %s\nSubject: %s\n\n%s""" % (from_who, destination, subject, messa
def send_email(destination, subject, message):
from_who = "My Name"
to_send = """\From: %s\nTo: %s\nSubject: %s\n\n%s""" % (from_who, destination, subject, message)
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(my_email_addr, my_pwrd)
server.sendmail(from_who, destination, message)
server.close()
except:
print "failed"
如果要在python中使用
SMTP
,则需要将数据作为字典发送
from email.parser import Parser
# This will parse out your to-, from-, and subject fields automatically
headers = Parser().parsestr(to_send)
# This will take care of the to- and from-fields for you
server.send_message(headers)
test.py 编辑 或者,您可以这样做:
to_send = string.join((
"From: %s" % from_whom,
"To: %s" % destination,
"Subject: %s" % subject,
"",
message
), "\r\n")
# ...
server.sendmail(from_whom, [destination], to_send)
# ...
我认为另一种方法更干净,但这取决于您。谢谢,但我所看到的smtplib示例中没有一个使用这种方法,而且他们报告说它是有效的。这是一种情况,您肯定需要将邮件作为字典发送-这就是
SMTP
的工作方式。您在之前有一个“\”来自。不确定这是否会破坏它,但它可能会。简言之,存在一些问题。杂散的\
和目的地
应作为列表发送。强烈推荐解析方法。
to_send = string.join((
"From: %s" % from_whom,
"To: %s" % destination,
"Subject: %s" % subject,
"",
message
), "\r\n")
# ...
server.sendmail(from_whom, [destination], to_send)
# ...