致电给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也可用。