0

I am trying to send emails in HTML format to different recipients from an excel sheet. Every time I try the emails are sent but the body of the message is received literally with the html code not being able to display correctly. How can I write correctly to send HTML messages visualizing correctly?

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import pandas as pd
import smtplib
import email.message

msg = email.message.Message()

password = "XXXXXX"
msg['From'] = "xxxxxx@xxx.com"

email_list = pd.read_excel(open('C:\\Users\\desktop\\listaemail.xlsx','rb'), sheet_name = 'Hoja1')

all_names = email_list['Name']
all_emails = email_list['Email']
all_subjects = email_list['Subject']
all_messages = email_list['Message']

for idx in range(len(all_emails)):

    name = all_names[idx]
    email = all_emails[idx]
    subject = all_subjects[idx]
    email_content = all_messages[idx]

    full_email = ("From: {0} <{1}>\nTo: {2} <{3}>\nSubject: {4}\n\n{5}".format("Marco", msg['From'], name, email, subject, email_content))

    try:
            msg.add_header('Content-Type', 'text/html')
            msg.set_payload(email_content)
            server = smtplib.SMTP('smtp.office365.com: 587')
            server.starttls()
            server.login(msg['From'], password)
            server.sendmail(msg['From'], [email], full_email)
            print ("successfully sent email to %s:" % ([email]))

    except Exception as e:
        print('Email to {} could not be sent :( because {}\n\n'.format(email, str(e)))

server.quit()

print ("Sent")
Chris
  • 112,704
  • 77
  • 249
  • 231
  • Please don't SHOUT. Stack Overflow will automatically format your title as a heading. You don't need to put it in all caps. – Chris Feb 29 '20 at 15:20
  • Aside: if this is new code, consider upgrading to Python 3 (ideally the latest release, which is 3.8.2 at the moment). Python 2 is no longer officially receiving support, and Python 3 has a bunch of cool new features. – Chris Feb 29 '20 at 15:22
  • Does this answer your question? [Sending HTML email using Python](https://stackoverflow.com/questions/882712/sending-html-email-using-python) – Chris Feb 29 '20 at 15:24
  • it doesn't answer my question Chris – Marco Araya Arriagada Mar 02 '20 at 16:10

1 Answers1

0

before sending the email you need to specify which part of your email is an HTML and which are not, simplye attach it with msg.attach and specify that it is a MIMEText

from email.mime.text import MIMEText


msg.attach(MIMEText(html_content, 'html'))
Manish Chaudhary
  • 475
  • 6
  • 14