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

Python使用emailMIMEText发送带附件的HTML电子邮件

发布时间:2023-12-23 09:53:20

Python中可以使用email.mime.text模块中的MIMEText类实现发送带附件的HTML电子邮件。以下是一个使用例子:

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

# 邮件内容
message = MIMEMultipart()
message["Subject"] = "带附件的HTML邮件"
message["From"] = "sender@example.com"
message["To"] = "recipient@example.com"

# HTML内容
html_content = """
<html>
<body>
<h1>Hello, World!</h1>
<p>This is a sample HTML email with attachments.</p>
</body>
</html>
"""
html_part = MIMEText(html_content, "html")
message.attach(html_part)

# 附件
attachment_path = "path_to_attachment_file"
with open(attachment_path, "rb") as attachment:
    attachment_part = MIMEApplication(attachment.read())
    attachment_part.add_header("Content-Disposition", "attachment", filename="filename.ext")
    message.attach(attachment_part)

# 发送邮件
smtp_host = "smtp.example.com"
smtp_port = 587
smtp_username = "username"
smtp_password = "password"

with smtplib.SMTP(smtp_host, smtp_port) as smtp:
    smtp.starttls()
    smtp.login(smtp_username, smtp_password)
    smtp.send_message(message)

print("邮件发送成功!")

在上面的例子中,我们首先创建了一个MIMEMultipart对象,用于存储邮件的主要信息,例如主题、发件人、收件人等。

然后,我们创建了一个MIMEText对象,将HTML内容添加到MIMEText对象中,并将MIMEText对象添加到MIMEMultipart对象中。这样,HTML内容就作为邮件的一部分被包含在了邮件中。

接下来,我们创建了一个MIMEApplication对象,用于表示附件。将附件的内容读取并添加到MIMEApplication对象中,并通过设置“Content-Disposition”头部来指定附件的文件名。最后,将附件对象添加到MIMEMultipart对象中。

最后,我们使用smtplib模块连接到SMTP服务器,设置TLS加密,验证登录,并通过send_message()方法发送邮件。

备注:请根据实际情况修改示例中的邮件主题、发件人、收件人、SMTP服务器等参数。