任何人都可以看到为什么以下代码成功发送电子邮件但它显示为来自发件人的电子邮件地址而不是收件人收件箱中的发件人姓名,主题显示为"没有主题& #34;在他们的收件箱中。提前谢谢。
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"
答案 0 :(得分:0)
如果你想在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
from email.parser import Parser
from_whom = "hello@example.com"
destination = "world@example.com"
subject = "Foobar!"
message = "Bar bar binks"
to_send = """From: %s\nTo: %s\nSubject: %s\n\n%s""" % (from_whom, destination, subject, message)
print(to_send)
headers = Parser().parsestr(to_send)
print(headers["To"]) # world@example.com
print(headers["From"]) # hello@example.com
print(headers["Subject"]) # Foobar!
修改强>
或者,你可以这样做:
to_send = string.join((
"From: %s" % from_whom,
"To: %s" % destination,
"Subject: %s" % subject,
"",
message
), "\r\n")
# ...
server.sendmail(from_whom, [destination], to_send)
# ...
我认为另一种方式更清洁,但这取决于你。