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

Python邮件发送指南:使用email.mime.base模块的MIMEBase()函数创建附件邮件的实现方法

发布时间:2023-12-28 00:19:18

Python的email模块提供了一种方便的方式来发送邮件。使用email.mime.base模块的MIMEBase()函数,可以创建附件邮件。以下是使用MIMEBase()函数创建附件邮件的实现方法,并附带一个使用例子。

实现方法:

1. 导入所需模块

from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

2. 创建一个MIMEMultipart对象,并设置邮件的基本信息

msg = MIMEMultipart()
msg['From'] = "sender@example.com"  # 发件人邮箱
msg['To'] = "receiver@example.com"  # 收件人邮箱
msg['Subject'] = "附件邮件"  # 邮件主题

3. 读取要发送的附件,并将其添加到MIMEMultipart对象中

attachment_path = "path/to/attachment.txt"  # 附件路径
attachment_name = "attachment.txt"  # 附件名称

attachment = open(attachment_path, "rb")  # 以二进制读取附件文件
part = MIMEBase('application', 'octet-stream')  # 创建附件对象
part.set_payload((attachment).read())  # 将附件内容添加到附件对象
encoders.encode_base64(part)  # 对附件进行编码
part.add_header('Content-Disposition', "attachment; filename= %s" % attachment_name)  # 设置附件名称
msg.attach(part)  # 将附件对象添加到邮件对象中

4. 使用SMTP协议发送邮件

import smtplib

server = smtplib.SMTP('smtp.example.com', 587)  # 选择邮件服务器和端口
server.starttls()  # 启动TLS加密
server.login("sender@example.com", "password")  # 邮箱登录
text = msg.as_string()  # 将邮件对象转换为字符串
server.sendmail("sender@example.com", "receiver@example.com", text)  # 发送邮件
server.quit()  # 退出服务器

使用例子:

以下是一个使用MIMEBase()函数创建附件邮件的示例代码。在这个示例中,我们将发送一个名为“attachment.txt”的文本文件作为附件。

from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import smtplib

msg = MIMEMultipart()
msg['From'] = "sender@example.com"
msg['To'] = "receiver@example.com"
msg['Subject'] = "附件邮件"

attachment_path = "path/to/attachment.txt"
attachment_name = "attachment.txt"

attachment = open(attachment_path, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % attachment_name)
msg.attach(part)

server = smtplib.SMTP('smtp.example.com', 587)
server.starttls()
server.login("sender@example.com", "password")
text = msg.as_string()
server.sendmail("sender@example.com", "receiver@example.com", text)
server.quit()

通过上述步骤,您可以使用email.mime.base模块的MIMEBase()函数创建包含附件的邮件,并通过SMTP协议发送。请确保替换示例代码中的发送人、接收人和附件路径,并提供正确的SMTP服务器和登录凭据。