python邮件没有主题通过

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代码来发送。请注意,在这两个步骤中都会重复一些类似于和来自地址的数据。

+0

这是否在一个单独的文本文件?电子邮件发送到一个很好,来自和身体...只是没有主题 – fuelcell 2011-04-05 18:51:39

+0

明白了。谢谢, – fuelcell 2011-04-05 19:04:25

您需要填写"Subject" header

有关如何正确执行此操作的一些示例,请参阅以下页面:18.1.11. email: Examples。第一个或多或少的你想要的。

+0

感谢您的意见。我没有运气试过这个。 – fuelcell 2011-04-05 17:06:58

+1

如果您尝试过,并且无法使用,请*发布您的代码。* – kindall 2011-04-05 17:23:05

+0

不知道如何在评论框中格式化 – fuelcell 2011-04-05 17:39:11

使用Python的电子邮件模块生成格式正确的RFC-822兼容电子邮件 - 包括主题等。自己动手做是容易出错的。

http://docs.python.org/library/email