我有一个python代码,用来发送一封带有附件的电子邮件,我已经归结为:
#!/usr/bin/python
import os, re
import sys
import smtplib
#from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.MIMEText import MIMEText
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
sender = 'me@gmail.com'
password = "e45dt4iamkiddingthisisnotmypassword"
recipient = 'he@gmail.com'
subject = 'Python emaillib Test'
message = 'Images attached.'
def main():
msg = MIMEMultipart()
msg['Subject'] = 'Python emaillib Test'
msg['To'] = recipient
msg['From'] = sender
msg.attach('/tmp/images/a.gif')
part = MIMEText('text', "plain")
part.set_payload(message)
msg.attach(part)
session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.ehlo()
session.starttls()
session.ehlo
session.login(sender, password)
# my_message=msg.as_string()
qwertyuiop=msg
session.sendmail(sender, recipient, qwertyuiop.as_string())
session.quit()
if __name__ == '__main__':
main()
我在运行时遇到这个错误:
Traceback (most recent call last):
File "./abcd.py", line 49, in <module>
main()
File "./abcd.py", line 44, in main
session.sendmail(sender, recipient, qwertyuiop.as_string())
File "/usr/lib/python2.7/email/message.py", line 137, in as_string
g.flatten(self, unixfrom=unixfrom)
File "/usr/lib/python2.7/email/generator.py", line 83, in flatten
self._write(msg)
File "/usr/lib/python2.7/email/generator.py", line 108, in _write
self._dispatch(msg)
File "/usr/lib/python2.7/email/generator.py", line 134, in _dispatch
meth(msg)
File "/usr/lib/python2.7/email/generator.py", line 203, in _handle_multipart
g.flatten(part, unixfrom=False)
File "/usr/lib/python2.7/email/generator.py", line 83, in flatten
self._write(msg)
File "/usr/lib/python2.7/email/generator.py", line 108, in _write
self._dispatch(msg)
File "/usr/lib/python2.7/email/generator.py", line 125, in _dispatch
main = msg.get_content_maintype()
AttributeError: 'str' object has no attribute 'get_content_maintype'
我认为这与msg.attach("/tmp/images/a.gif")有关,但我不确定。问题的根源是qwertyuiop.as_string()。
问题是msg.attach()
附加了另一条消息,而不是字符串/文件名。您需要创建一个MIMEImage
对象并附加它:
# instead of msg.attach('/tmp/images/a.gif')...
fp = open('/tmp/images/a.gif', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msg.attach(msgImage)
示例改编自此处
如果您想要图像以外的类型,请签出http://docs.python.org/library/email.mime.html.
qwertyuiop.as_string()
行出现错误的原因是,在调用as_string()
之前,不会解析消息。