Python smtplib sendmail()无法与主题/正文一起使用 [英] Python smtplib sendmail() not working with subject / body

查看:51
本文介绍了Python smtplib sendmail()无法与主题/正文一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我尝试使用 sendmail(sender,reciever,message)时,它都会成功发送电子邮件,并且主题行很好,但邮件的正文电子邮件总是丢失。

Whenever I try to use sendmail(sender,reciever,message), it sends the email successfully, and the subject line is fine, but the 'body' of the e-mail is always missing.

这是我的完整代码:

s = smtplib.SMTP("smtp.gmail.com",587)
s.ehlo()
s.starttls()
s.login(sender,password)
message = """From %s
Subject: %s
This is the body part""" % (sender,subject)
s.sendmail(sender,reciever,message)
s.quit()

为什么不接收尸体?

推荐答案

您在主题和正文之间缺少一个额外的空白行,如官方文档的示例(释义):

You're missing an extra blank line between the Subject and the body, as outlined in the official documentation's example (paraphrased):

msg = "From: %s\r\nTo: %s\r\n\r\nBody text"

无论如何,我都会遵循建议文档中的说明,而是使用电子邮件包中的Message对象。这样,您不必担心正确格式化字符串,只需执行以下操作:

In any case, I would follow the recommendations in the documentation and use the Message object from the email package instead. That way you don't have to worry about formatting the string correctly, and can just do this:

msg = EmailMessage()
msg['Subject'] = "Subject"
msg['From'] = Address("Name", "mailbox", "domain")
msg['To'] = (Address("Name Too", "test", "example.com"),
             Address("And so on", "so", "forth"))
msg.set_content("The body of the e-mail")

with smtplib.SMTP("smtp.gmail.com", 587) as s:
    s.send_message(msg)

请参见官方文档的示例以获取更多信息。

See the official documentation's examples for more.

这篇关于Python smtplib sendmail()无法与主题/正文一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆