Send HTML and plain text as body in emails with Python

403 Views Asked by At

Send HTML content in email using Python? I can send simple texts or i can send HTML content, but not both at the same time. I used SMTP built in lib in Python

text ='Hi,\n Just for testing"
with open('samplefile.html') as fp:
   body = fp.read()

part1 = MIMEText(text,'plain')
part2 = MIMEText(body,'html)

msg.attach(part1)
msg.attach(part2)

Email is sent but only text file is showing in the content and html send as attachement file. If i remove part1 and it only sends HTML file , then I am able to see in the email content.

But not able to see both text and HTML in the body content at once.

1

There are 1 best solutions below

2
On

Try below python code:

Note : I am reading all the arguments from email.ini file (username, Pswd, smtp server details..etc)

def email(self, formatting):

    config = ConfigParser()
    config.read("email.ini")
    msg = MIMEMultipart()

    msg['To'] = 'abc.test@gmail'
    msg['Subject'] = 'INFO: HTML WITH TEXT'

    if formatting == 1:
        html =open("Table.htm","r")
        msg.attach(MIMEText(html.read(), 'html'))
    else:
        body = MIMEText(body)
        msg.attach(body)
    part = MIMEBase('application', 'octet-stream')
    server = smtplib.SMTP(config.get('smtp','host'))
    server.starttls()
    server.login(config.get('smtp','user'),config.get('smtp','password'))
    text = msg.as_string()
    server.sendmail(config.get('email','fromaddr'), msg["To"].split(",") ,text)
    server.quit()
    print("sending email to "+config.get('email','toaddr'))

def main():
    email = sendEmail()
    email.email(1)

if __name__ == "__main__": main()