I have python code intended to send an email with an attachment, and I've come down 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 = '[email protected]'
password = "e45dt4iamkiddingthisisnotmypassword"
recipient = '[email protected]'
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 when running:
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 that it has to do with msg.attach("/tmp/images/a.gif") but I'm not sure. The source of the problem is qwertyuiop.as_string() though.
The problem is that msg.attach()
attaches another message, not a string/filename. You need to create a MIMEImage
object and attach that:
# 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 want types other than Images, check out http://docs.python.org/library/email.mime.html.
The reason you're getting the error on the qwertyuiop.as_string()
line is that the message isn't parsed until you call as_string()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With