Search code examples
pythonpython-2.7emailsendmailmime

How to add a body text to a multipart email in python 2?


I am successfully sending mails with attachment using python 2. But the mails still have no body content.

Can someone please tell me how can I add a body text along with attachment and subject.

My current code is:

import smtplib, os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import Encoders
from email.mime.text import MIMEText


SUBJECT = "Email Data"
emaillist=['xyz@hotmail.com']
msg = MIMEMultipart('mixed')
msg['Subject'] = 'SUBJECT '
msg['From'] = 'abc@gmail.com'
msg['To'] = ', '.join(emaillist)



part = MIMEBase('application', "octet-stream")

part.set_payload(open('C:'+os.sep+'Desktop'+os.sep+'temp1.txt', `"rb").read())`
Encoders.encode_base64(part)

part.add_header('Content-Disposition', 'attachment; filename="output.txt"')

msg.attach(part)

server = smtplib.SMTP("smtp.gmail.com",587)
server.ehlo()
server.starttls()
server.login("abc@gmail.com", "password")

server.sendmail(msg['From'], emaillist , msg.as_string())

Solution

  • From https://docs.python.org/2/library/email-examples.html :

    text = "Here is the message body"
    html = """
    <html>
      <head></head>
      <body>
        <p>here is some html<br>
           Here is some link <a href="https://www.python.org">link</a>.
        </p>
      </body>
    </html>
    """
    
    part1 = MIMEText(text, 'plain')
    part2 = MIMEText(html, 'html')
    msg.attach(part1)
    msg.attach(part2)
    

    Insert this after msg.attach(part)