python邮件没有主题通过
问题描述:
我通过python发送Gmail,但我没有得到任何主题。我意识到我向你展示的代码没有任何主题,但我已经尝试过很多变体而没有成功。有人可以告诉我如何实施一个主题。这个主题每次都是一样的。python邮件没有主题通过
fromaddr = '[email protected]'
toaddrs = '[email protected]'
msg = 'Portal Test had an error'
#provide gmail user name and password
username = 'XXXX'
password = 'XXXXX'
# functions to send an email
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.ehlo()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
答
有在发出一个互联网电子邮件2重要的一步 - 创建一个RFC-2822的消息,然后使用SMTP发送它。您正在查看SMTP部分,但并未首先创建正确的消息。这样做比较容易证明。
>>> from email.mime.text import MIMEText
>>>
>>> fromaddr = '[email protected]'
>>> toaddrs = '[email protected]'
>>> subject = 'This is an important message'
>>> content = 'Portal Test had an error'
>>>
>>> # constructing a RFC 2822 message
... msg = MIMEText(content)
>>> msg['From'] = fromaddr
>>> msg['To'] = toaddrs
>>> msg['Subject'] = subject
一个RFC 2822的消息实在是一段文字,看起来像这样:
>>> print msg
From nobody Tue Apr 05 11:37:50 2011
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
From: [email protected]
To: [email protected]
Subject: This is an important message
Portal Test had an error
有了这个,你应该能够使用您的SMTP代码来发送。请注意,在这两个步骤中都会重复一些类似于和来自地址的数据。
这是否在一个单独的文本文件?电子邮件发送到一个很好,来自和身体...只是没有主题 – fuelcell 2011-04-05 18:51:39
明白了。谢谢, – fuelcell 2011-04-05 19:04:25