How to add a "Body" to a python mime multipart(has attachment) email -
i using following snippet send email attachment. want add message in body describing attachment, how do it? email blank body.
msg = mimemultipart() msg["from"] = emailfrom msg["to"] = emailto msg["subject"] = subject ctype, encoding = mimetypes.guess_type(filetosend) if ctype none or encoding not none: ctype = "application/octet-stream" maintype, subtype = ctype.split("/", 1) if maintype == "text": fp = open(filetosend) # note: should handle calculating charset attachment = mimetext(fp.read(), _subtype=subtype) fp.close() elif maintype == "image": fp = open(filetosend, "rb") attachment = mimeimage(fp.read(), _subtype=subtype) fp.close() elif maintype == "audio": fp = open(filetosend, "rb") attachment = mimeaudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(filetosend, "rb") attachment = mimebase(maintype, subtype) attachment.set_payload(fp.read()) fp.close() encoders.encode_base64(attachment) attachment.add_header("content-disposition", "attachment", filename=os.path.basename(filetosend)) msg.attach(attachment) server = smtplib.smtp('localhost') server.sendmail(emailfrom, emailto, msg.as_string()) server.quit()
try this:
from email.mimemultipart import mimemultipart email.mimetext import mimetext ... msg = mimemultipart("related") msg["from"] = emailfrom msg["to"] = emailto msg["subject"] = subject body_container = mimemultipart('alternative') body_container.attach(mimetext( plain_text_body.encode('utf-8'), 'plain', 'utf-8')) msg.attach(body_container) ...
then attach attachments. can attach both 'plain' , 'html' body. in case attach second mimetext(html_body, 'html', 'utf-8')
body_container
Comments
Post a Comment