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

使用MIMEText发送HTML格式邮件的Python代码

发布时间:2023-12-11 13:46:23

发送HTML格式的邮件需要使用Python的smtplib和email模块。smtplib模块用于创建并发送邮件,email模块用于创建邮件内容。

下面是一个示例代码,演示如何使用MIMEText发送HTML格式的邮件:

import smtplib
from email.mime.text import MIMEText

def send_html_email(subject, html_content, sender, receiver, smtp_server, smtp_port, username, password):
    # 创建邮件内容
    message = MIMEText(html_content, "html")
    message["Subject"] = subject
    message["From"] = sender
    message["To"] = receiver

    # 发送邮件
    try:
        server = smtplib.SMTP(smtp_server, smtp_port)  # 连接SMTP服务器
        server.starttls()  # 开启TLS加密
        server.login(username, password)  # 登录SMTP服务器
        server.sendmail(sender, receiver, message.as_string())  # 发送邮件
        server.quit()  # 断开与SMTP服务器的连接
        print("邮件发送成功")
    except Exception as e:
        print("邮件发送失败:", str(e))


# 使用例子
subject = "HTML格式邮件示例"
html_content = """
<html>
<body>
<h1>这是一封HTML格式的邮件示例</h1>
<p>这是邮件的内容,可以使用HTML标签格式化邮件内容。</p>
<p>比如,可以使用<h2>标签来创建二级标题。</h2></p>
</body>
</html>
"""
sender = "sender@example.com"
receiver = "receiver@example.com"
smtp_server = "smtp.example.com"
smtp_port = 25
username = "username"
password = "password"

send_html_email(subject, html_content, sender, receiver,
                smtp_server, smtp_port, username, password)

在上述代码中,我们首先导入了smtplib模块和MIMEText类。然后,我们定义了一个名为send_html_email的函数,该函数接受邮件的主题、HTML内容、发件人、收件人、SMTP服务器地址、SMTP端口号、SMTP用户名和SMTP密码等参数。

函数内部首先创建了一个MIMEText对象,并将HTML内容与"html"参数一起传递给MIMEText类的构造函数,以指定创建HTML格式的邮件内容。

然后,我们设置了邮件的主题、发件人和收件人,并封装了这些信息到邮件的message对象中。

接下来,我们使用smtplib模块连接到SMTP服务器,并使用starttls方法开启TLS加密。然后,我们使用login方法登录SMTP服务器,并使用sendmail方法发送邮件。最后,我们使用quit方法断开与SMTP服务器的连接。

在使用例子中,我们定义了邮件的主题和HTML内容。然后,我们指定了发件人、收件人、SMTP服务器地址、SMTP端口号、SMTP用户名和SMTP密码。最后,我们调用send_html_email函数发送邮件。

以上就是使用MIMEText发送HTML格式邮件的Python代码以及一个使用例子。你可以根据自己的邮件需求,替换相应的参数并使用该代码发送HTML格式的邮件。