欢迎访问宙启技术站
智能推送

使用MIMEApplication()在Python中发送包含HTML文件附件的邮件

发布时间:2023-12-24 23:43:23

要使用Python发送包含HTML文件附件的邮件,你可以使用MIMEApplication模块和MIMEMultipart模块。下面是一个具体的例子,该例子演示了如何发送一个包含HTML文件附件的邮件。

首先,你需要导入相应的模块:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText

接下来,你需要设置发送方和接收方的电子邮件地址,以及邮件的主题和正文:

sender = 'your_email@example.com'
receiver = 'recipient@example.com'
subject = 'Email with HTML attachment'
message = '<html><body><h1>HTML File Attachment</h1></body></html>'

然后,你可以创建一个MIMEMultipart对象,并设置邮件的发送方、接收方、主题和正文:

msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = subject
msg.attach(MIMEText(message, 'html'))

接下来,你可以通过open()函数打开要附加的HTML文件,并将其读取为一个字符串:

html_file = open('path_to_html_file.html', 'r')
html_content = html_file.read()
html_file.close()

然后,你可以将读取到的HTML内容作为附件添加到邮件中:

attachment = MIMEApplication(html_content)
attachment.add_header('Content-Disposition','attachment', filename='html_attachment.html')
msg.attach(attachment)

最后,你需要使用smtplib库来连接到一个SMTP服务器并发送邮件:

server = smtplib.SMTP('smtp.example.com', 587)
server.starttls()
server.login('your_email@example.com', 'your_password')
server.send_message(msg)
server.quit()

请确保将代码中的your_email@example.comrecipient@example.compath_to_html_file.htmlsmtp.example.com587your_password等部分替换为你自己的实际信息。

到此为止,你已经成功地创建了一个包含HTML文件附件的邮件,并使用Python发送出去了。