email modules and attachments that aren't there
Russell Bungay
bigmaddrongo at yahoo.co.uk
Tue Jan 10 04:53:37 EST 2006
Hello,
>>> main_msg['Content-type'] = 'Multipart/mixed'
>> Would it be the 'Content-Type' header? I've no expertise in this, but
>> doesn't 'multipart' mean 'has attachments'?
> Brilliant, thank you. A swift test on the number of attachments and
> changing the header suitably does the job.
That isn't quite all there is to it, the e-mail construction needs a
slight change as well. Roughly working code below.
Ta,
Russell
Code:
def sendEmail(msg_to, msg_from, msg_subject, message, attachments=[]):
main_msg = email.Message.Message()
main_msg['To'] = ', '.join(msg_to)
main_msg['From'] = msg_from
main_msg['Subject'] = msg_subject
main_msg['Date'] = email.Utils.formatdate(localtime=1)
main_msg['Message-ID'] = email.Utils.make_msgid()
main_msg['Mime-version'] = '1.0'
main_msg.preamble = 'Mime message\n'
main_msg.epilogue = ''
body_encoded = quopri.encodestring(message, 1)
if len(attachments) <> 0:
main_msg['Content-type'] = 'Multipart/mixed'
body_msg = email.Message.Message()
body_msg.add_header('Content-type', 'text/plain')
body_msg.add_header('Content-transfer-encoding',
'quoted-printable')
body_msg.set_payload(body_encoded)
main_msg.attach(body_msg)
for attachment in attachments:
content_type, ignored = mimetypes.guess_type(attachment)
if content_type == None:
content_type = 'application/octet-stream'
contents_encoded = cStringIO.StringIO()
attach_file = open(attachment, 'rb')
main_type = content_type[:content_type.find('/')]
if main_type == 'text':
cte = 'quoted-printable'
quopri.encode(attach_file, contents_encoded, 1)
else:
cte = 'base64'
base64.encode(attach_file, contents_encoded)
attach_file.close()
sub_msg = email.Message.Message()
sub_msg.add_header('Content-type', content_type, name=attachment)
sub_msg.add_header('Content-transfer-encoding', cte)
sub_msg.set_payload(contents_encoded.getvalue())
main_msg.attach(sub_msg)
else:
main_msg['Content-type'] = 'text/plain'
main_msg['Content-transfer-encoding'] = 'quoted-printable'
main_msg.set_payload(body_encoded)
smtp = smtplib.SMTP('server')
smtpfail = smtp.sendmail(msg_from, ', '.join(msg_to),
main_msg.as_string())
smtp.quit()
More information about the Python-list
mailing list