简体   繁体   English

从 Excel 发送 HTML 电子邮件

[英]Send HTML email from Excel

I am trying to send emails in HTML format to different recipients from an excel sheet.我正在尝试将 HTML 格式的电子邮件从 Excel 工作表发送给不同的收件人。 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.每次我尝试发送电子邮件时,都会收到邮件正文,但 html 代码无法正确显示。 How can I write correctly to send HTML messages visualizing correctly?如何正确编写以发送正确可视化的 HTML 消息?

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")

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在发送电子邮件之前,您需要指定电子邮件的哪一部分是 HTML,哪一部分不是,只需使用 msg.attach 附加它并指定它是 MIMEText

from email.mime.text import MIMEText


msg.attach(MIMEText(html_content, 'html'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM