如何为使用 Gmail 发送的电子邮件添加主题?

2024-02-05

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

import smtplib
fromx = '[email protected] /cdn-cgi/l/email-protection'
to  = '[email protected] /cdn-cgi/l/email-protection'
subject = 'subject' #Line that causes trouble
msg = 'example'
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.ehlo()
server.login('[email protected] /cdn-cgi/l/email-protection', 'password')
server.sendmail(fromx, to, subject , msg) #'subject'Causes trouble
server.quit()

错误行:

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

致电给smtplib.SMTP.sendmail()不需subject范围。看the doc https://docs.python.org/2/library/smtplib.html#smtplib.SMTP.sendmail有关如何调用它的说明。

主题行与所有其他标头一起作为消息的一部分以称为 RFC822 格式的格式包含在最初定义该格式的现已废弃的文档之后。让您的消息符合该格式,如下所示:

import smtplib
fromx = '[email protected] /cdn-cgi/l/email-protection'
to  = '[email protected] /cdn-cgi/l/email-protection'
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('[email protected] /cdn-cgi/l/email-protection', 'xxx')
server.sendmail(fromx, to, msg)
server.quit()

当然,使您的消息符合所有适当标准的更简单方法是使用 Pythonemail.message https://docs.python.org/2/library/email.message.html标准库,像这样:

import smtplib
from email.mime.text import MIMEText

fromx = '[email protected] /cdn-cgi/l/email-protection'
to  = '[email protected] /cdn-cgi/l/email-protection'
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('[email protected] /cdn-cgi/l/email-protection', 'xxx')
server.sendmail(fromx, to, msg.as_string())
server.quit()

其他例子 https://docs.python.org/2/library/email-examples.html#email-examples也可用。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何为使用 Gmail 发送的电子邮件添加主题? 的相关文章

随机推荐