Prev: Issues while building pyfsevents in python 3.1
Next: Performance of list.index - how to speed up a silly algorithm?
From: Alan Harris-Reid on 29 Apr 2010 16:06 Hi there, I want to send an email with an attachment using the following code (running under Python 3.1, greatly simplified to show example) from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText msg = MIMEMultipart() msg['From'] = from_addr msg['To'] = to_addr msg['Subject'] = subject msg.attach(MIMEText(body)) fp = open(att_file) att_msg = MIMEText(fp.read()) attachment = att_msg.add_header('Content-Disposition', 'attachment', filename=att_file) msg.attach(attachment) # set string to be sent as 3rd parameter to smptlib.SMTP.sendmail() send_string = msg.as_string() The attachment object msg1 returns 'email.mime.text.MIMEText' object at <address>', but when the att_msg.add_header(...) line runs the result is None, hence the program falls-over in msg.as_string() because no part of the attachment can have a None value. (Traceback shows "'NoneType' object has no attribute 'get_content_maintype'" in line 118 of _dispatch in generator.py, many levels down from msg.as_string()) Has anyone any idea what the cause of the problem might be? Any help would be appreciated. Alan Harris-Reid
From: Chris Rebert on 29 Apr 2010 16:37
On Thu, Apr 29, 2010 at 1:06 PM, Alan Harris-Reid <aharrisreid(a)googlemail.com> wrote: > Hi there, > > I want to send an email with an attachment using the following code (running > under Python 3.1, greatly simplified to show example) > > Â from email.mime.multipart import MIMEMultipart > Â from email.mime.text import MIMEText > > Â msg = MIMEMultipart() > Â msg['From'] = from_addr > Â msg['To'] = to_addr > Â msg['Subject'] = subject > Â msg.attach(MIMEText(body)) > > Â fp = open(att_file) > Â att_msg = MIMEText(fp.read()) > Â attachment = att_msg.add_header('Content-Disposition', 'attachment', > filename=att_file) > Â msg.attach(attachment) > > Â # set string to be sent as 3rd parameter to smptlib.SMTP.sendmail() > Â send_string = msg.as_string() > > > The attachment object msg1 returns 'email.mime.text.MIMEText' object at > <address>', but when the att_msg.add_header(...) line runs the result is > None, hence the program falls-over in msg.as_string() because no part of the > attachment can have a None value. Â (Traceback shows "'NoneType' object has > no attribute 'get_content_maintype'" in line 118 of _dispatch in > generator.py, many levels down from msg.as_string()) > > Has anyone any idea what the cause of the problem might be? Â Any help would > be appreciated. ..add_header() modifies the MIMEText object *in-place*; per Python conventions, mutator methods return None; hence, attachment = None. Try instead (untested): att_msg.add_header('Content-Disposition', 'attachment', filename=att_file) msg.attach(att_msg) Cheers, Chris -- http://blog.rebertia.com |