A program sending email through Python outputs with an AttributeError: 'str' object does not have the attribute 'get_content_maintype' '"

I have python code designed to send email with an attachment, and I got to this:

#!/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() 

And I get this error on startup:

 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' 

I assume this is related to msg.attach ("/tmp/images/a.gif"), but I'm not sure. The source of the problem is qwertyuiop.as_string (), though.

+4
source share
1 answer

The problem is that msg.attach() attaching a different message, not a line / file name. You need to create a MIMEImage object and attach it:

 # instead of msg.attach('/tmp/images/a.gif')... fp = open('/tmp/images/a.gif', 'rb') msgImage = MIMEImage(fp.read()) fp.close() msg.attach(msgImage) 

Example adapted from here

If you need types other than images, select http://docs.python.org/library/email.mime.html .

The reason you get an error in the qwertyuiop.as_string() line is because the message is not parsed until you call as_string() .

+5
source

Source: https://habr.com/ru/post/1401693/


All Articles