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

使用Python发送HTML格式的邮件(使用email.MIMEText)

发布时间:2023-12-23 09:55:38

邮件是一种常用的通信方式,通过电子邮件可以方便地发送和接收信息。Python提供了email模块,用于处理邮件相关的操作。

email模块中的MIMEText类可以用来创建HTML格式的邮件内容。可以通过设置subtype参数为html来指定内容类型为HTML。

下面是一个使用email.MIMEText发送HTML格式邮件的例子:

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

def send_email(sender_email, sender_password, receiver_email, subject, html_content):
    # 创建邮件对象
    msg = MIMEMultipart()

    # 设置邮件内容
    msg.attach(MIMEText(html_content, 'html'))

    # 设置邮件主题
    msg['Subject'] = subject

    # 设置发件人和收件人
    msg['From'] = sender_email
    msg['To'] = receiver_email

    # 创建SMTP对象
    smtp = smtplib.SMTP('smtp.gmail.com', 587)

    # 开启TLS加密
    smtp.starttls()

    # 登录邮箱
    smtp.login(sender_email, sender_password)

    # 发送邮件
    smtp.send_message(msg)

    # 关闭SMTP连接
    smtp.quit()

# 示例用法
sender_email = 'your_email@gmail.com'
sender_password = 'your_password'
receiver_email = 'receiver_email@example.com'
subject = 'HTML Email Example'
html_content = """
<html>
<head></head>
<body>
<h1>This is an HTML email</h1>
<p>This email is sent using Python.</p>
<p>You can include HTML tags in the email content.</p>
</body>
</html>
"""
send_email(sender_email, sender_password, receiver_email, subject, html_content)

在上面的示例中,send_email函数接收发件人邮箱、发件人密码、收件人邮箱、邮件主题和HTML内容作为参数。该函数创建一个MIMEMultipart对象,将HTML内容以MIMEText的形式添加到邮件对象中。然后,设置邮件主题、发件人和收件人等信息,并使用SMTP协议发送邮件。

需要注意的是,发送邮件之前需要先在SMTP服务器上开启SMTP服务并获取相应的服务器地址和端口号。

以上是一个简单的例子,用于发送带有HTML格式的邮件。可以根据实际需求对邮件的内容和格式进行调整。