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

如何在Python中使用email.mime.multipart库发送HTML格式的邮件

发布时间:2023-12-14 11:48:19

Python中的email.mime.multipart库可以用于发送包含多个部分的邮件,其中一个部分可以是HTML格式的内容。下面是使用email.mime.multipart库发送HTML格式邮件的步骤和示例代码。

步骤1:导入必要的库和模块

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

步骤2:创建邮件对象并设置发件人、收件人和主题

msg = MIMEMultipart()
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
msg['Subject'] = 'HTML Email Example'

步骤3:创建HTML邮件的正文内容,并将其作为MIMEText对象添加到邮件对象中

html_content = """
<html>
<body>
<h1>This is an HTML email</h1>
<p>Here is the content of the email, written in HTML format.</p>
</body>
</html>
"""
html_part = MIMEText(html_content, 'html')
msg.attach(html_part)

步骤4:连接SMTP服务器并发送邮件

smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'username'
smtp_password = 'password'

with smtplib.SMTP(smtp_server, smtp_port) as server:
    server.starttls()
    server.login(smtp_username, smtp_password)
    server.sendmail(msg['From'], msg['To'], msg.as_string())

完整的代码示例:

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

msg = MIMEMultipart()
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
msg['Subject'] = 'HTML Email Example'

html_content = """
<html>
<body>
<h1>This is an HTML email</h1>
<p>Here is the content of the email, written in HTML format.</p>
</body>
</html>
"""
html_part = MIMEText(html_content, 'html')
msg.attach(html_part)

smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'username'
smtp_password = 'password'

with smtplib.SMTP(smtp_server, smtp_port) as server:
    server.starttls()
    server.login(smtp_username, smtp_password)
    server.sendmail(msg['From'], msg['To'], msg.as_string())

以上代码会创建一个带有HTML格式内容的邮件并发送到指定的收件人。确保将实际的SMTP服务器地址、端口、发件人和收件人地址以及登录凭据正确地替换在代码中。

注意:要发送HTML邮件,收件人的邮件客户端也需要支持HTML格式,通常大部分现代邮件客户端都可以正确地显示HTML格式的邮件内容。