【问题标题】:How to add a subject to an email being sent with gmail?如何在使用 gmail 发送的电子邮件中添加主题?
【发布时间】:2016-09-16 21:03:32
【问题描述】:

我正在尝试使用 GMAIL 发送带有主题和消息的电子邮件。我已经成功地使用 GMAIL 发送了一封电子邮件,而没有实现 subject 并且也能够收到电子邮件。但是,每当我尝试添加主题时,程序就无法正常工作。

import smtplib
fromx = 'email@gmail.com'
to  = 'email1@gmail.com'
subject = 'subject' #Line that causes trouble
msg = 'example'
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.ehlo()
server.login('email@gmail.com', 'password')
server.sendmail(fromx, to, subject , msg) #'subject'Causes trouble
server.quit()

错误行:

server.sendmail(fromx, to, subject , msg) #'subject'Causes trouble

【问题讨论】:

标签: python python-2.7 email gmail subject


【解决方案1】:

smtplib.SMTP.sendmail() 的调用不采用subject 参数。有关如何调用它的说明,请参阅the doc

主题行以及所有其他标头以称为 RFC822 格式的格式包含在邮件中,位于最初定义该格式的现已过时的文档之后。使您的消息符合该格式,如下所示:

import smtplib
fromx = 'xxx@gmail.com'
to  = 'xxx@gmail.com'
subject = 'subject' #Line that causes trouble
msg = 'Subject:{}\n\nexample'.format(subject)
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.ehlo()
server.login('xxx@gmail.com', 'xxx')
server.sendmail(fromx, to, msg)
server.quit()

当然,使您的消息符合所有适当标准的更简单方法是使用 Python email.message 标准库,如下所示:

import smtplib
from email.mime.text import MIMEText

fromx = 'xxx@gmail.com'
to  = 'xxx@gmail.com'
msg = MIMEText('example')
msg['Subject'] = 'subject'
msg['From'] = fromx
msg['To'] = to

server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.ehlo()
server.login('xxx@gmail.com', 'xxx')
server.sendmail(fromx, to, msg.as_string())
server.quit()

Other examples 也可用。

【讨论】:

  • 谢谢罗伯!很好的解释!真是太感谢你了!
【解决方案2】:

或者只使用像yagmail 这样的包。免责声明:我是维护者。

import yagmail
yag = yagmail.SMTP("email.gmail.com", "password")
yag.send("email1.gmail.com", "subject", "contents")

使用pip install yagmail安装

【讨论】:

  • 我之前确实尝试过这个。好像没用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-14
  • 1970-01-01
  • 2014-08-09
  • 2013-08-11
  • 2015-04-29
  • 2015-05-29
相关资源
最近更新 更多