Hello all,
I have written a short function, based on a recipe in the Python
Cookbook, that sends an e-mail. The function takes arguments that
define who the e-mail is to, from, the subject, the body and an optional
list of attachments.
The function works also perfectly, bar one slight problem. If you
attempt to send an e-mail with just a body and no attachments, the
receiving client still thinks that there is an attachment (so far tested
in Mozilla Thunderbird and the Yahoo! webmail client). Although this
clearly isn't a major problem, it is irritating and I am hoping to use
my code at work. Obviously I can't be sending out badly formed e-mails
to my clients.
I can't for the life of me work out why. I have compared my code to
every example that I can find in the Python documentation, on the
archives of this newsgroup and of the Python Tutor list, and one or two
random searches but can't see what is happening. Any advice or
suggestions would be welcome.
Thank you for your help,
Russell Bungay
--
The Duck Quacks:
http://www-users.york.ac.uk/~rb502/ - Homepage
http://www-users.york.ac.uk/~rb502/blog/quack.shtml - Blog
http://www.flickr.com/photos/lsnduck/ - Photos
Code:
def sendEmail(msg_t o, msg_from, msg_subject, message, attachments=[]):
main_msg = email.Message.M essage()
main_msg['To'] = ', '.join(msg_to)
main_msg['From'] = msg_from
main_msg['Subject'] = msg_subject
main_msg['Date'] = email.Utils.for matdate(localti me=1)
main_msg['Message-ID'] = email.Utils.mak e_msgid()
main_msg['Mime-version'] = '1.0'
main_msg['Content-type'] = 'Multipart/mixed'
main_msg.preamb le = 'Mime message\n'
main_msg.epilog ue = ''
body_encoded = quopri.encodest ring(message, 1)
body_msg = email.Message.M essage()
body_msg.add_he ader('Content-type', 'text/plain')
body_msg.add_he ader('Content-transfer-encoding', 'quoted-printable')
body_msg.set_pa yload(body_enco ded)
main_msg.attach (body_msg)
for attachment in attachments:
content_type, ignored = mimetypes.guess _type(attachmen t)
if content_type == None:
content_type = 'application/octet-stream'
contents_encode d = cStingIO.String IO()
attach_file = open(attachment , 'rb')
main_type = content_type[:content_type.f ind('/')]
if main_type == 'text':
cte = 'quoted-printable'
quopri.encode(a ttach_file, contents_encode d, 1)
else:
cte = 'base64'
base64.encode(a ttach_file, contents_encode d)
attach_file.clo se()
sub_msg = email.Message.M essage()
sub_msg.add_hea der('Content-type', content_type, name=attachment )
sub_msg.add_hea der('Content-transfer-encoding', cte)
sub_msg.set_pay load(contents_e ncoded.getvalue ())
main_msg.attach (sub_msg)
smtp = smtplib.SMTP(se rver)
smtpfail = smtp.sendmail(m sg_from, ', '.join(msg_to),
main_msg.as_str ing())
smtp.quit()