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")
ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257

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
  • 498
  • 6
  • 14