Reise45
Reise45

Reputation: 1203

How to add a "Body" to a python mime multipart(has attachment) email

I am using the following snippet to send an email with an attachment. I want to add a message in the body describing the attachment, how do I do it? Currently I get the email with a blank body.

msg = MIMEMultipart()
    msg["From"] = emailfrom
    msg["To"] = emailto
    msg["Subject"] = subject



    ctype, encoding = mimetypes.guess_type(fileToSend)
    if ctype is None or encoding is not None:
        ctype = "application/octet-stream"

    maintype, subtype = ctype.split("/", 1)

    if maintype == "text":
        fp = open(fileToSend)
        # Note: we should handle calculating the 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()

Upvotes: 3

Views: 3984

Answers (2)

Reise45
Reise45

Reputation: 1203

This is how I did it:

body = "Text for body"
msg.attach(MIMEText(body,'plain'))

I did it after declaring subject and before attaching the file.

Upvotes: 4

knitti
knitti

Reputation: 7033

Try something like this:

from email.MIMEMultipart import MIMEMultipart
from 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 your attachments. You can also attach both a 'plain' and a 'html' body. In this case you would attach a second MIMEText(html_body, 'html', 'UTF-8') to the body_container

Upvotes: 2

Related Questions