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

MIMEText()方法简单示例(Python)

发布时间:2024-01-03 04:08:06

MIMEText 是一个用于创建 MIME 文本的类。它可以用于创建纯文本消息或包含 HTML 内容的消息。MIMEText 类有以下几个参数:

- _text: 消息的文本内容。

- _subtype: 指定 MIME 子类型,可以是 'plain'(纯文本)或 'html'(包含 HTML 内容)。

- _charset: 指定字符编码,默认为 'us-ascii'。

- _headers: 消息的头部信息,可以是一个字典或者一个类似于 [('Content-type', 'text/plain'), ('Content-Disposition', 'attachment; filename="example.txt"')] 的列表。

下面是一个简单的示例,展示如何使用 MIMEText 创建一个纯文本消息:

from email.mime.text import MIMEText

# 创建消息对象
msg = MIMEText("Hello, World!")

# 添加邮件头部信息
msg['Subject'] = 'Simple email with MIMEText'
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'

# 打印消息内容
print(msg.as_string())

输出:

Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Subject: Simple email with MIMEText
From: sender@example.com
To: recipient@example.com

Hello, World!

上面的示例中,我们通过传递一个字符串作为 _text 参数来创建了一个纯文本消息。然后,我们使用键值对的形式为消息添加了头部信息,包括主题、发件人和收件人。最后,我们使用 as_string() 方法将消息内容转换为字符串,并打印出来。

如果你想创建一个包含 HTML 内容的消息,你可以将 _subtype 参数设置为 'html',然后将 HTML 内容作为字符串传递给 _text 参数。

from email.mime.text import MIMEText

# 创建消息对象
msg = MIMEText("<h1>Hello, World!</h1>", _subtype='html')

# 添加邮件头部信息
msg['Subject'] = 'Simple email with HTML content'
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'

# 打印消息内容
print(msg.as_string())

输出:

Content-Type: text/html; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Subject: Simple email with HTML content
From: sender@example.com
To: recipient@example.com

<h1>Hello, World!</h1>

上面的示例中,我们将 _subtype 参数设置为 'html',然后将 HTML 格式的文本作为字符串传递给 _text 参数。

这就是使用 MIMEText 方法创建纯文本或包含 HTML 内容的消息的简单示例。你可以根据自己的需求来自定义消息的内容和头部信息。