使用Python的email.mime.multipart模块发送带附件的邮件示例
发布时间:2023-12-26 08:31:00
Python的email.mime.multipart模块可以用来发送带附件的邮件。下面是一个示例代码,演示了如何使用这个模块发送带有附件的邮件。
首先,我们需要导入相关的模块和类:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication
接下来,我们需要设置邮件的发送者、接收者、主题和附件:
# 设置邮件相关信息 sender = 'sender@example.com' receiver = 'receiver@example.com' subject = 'Email with attachment' # 创建一个带附件的邮件对象 message = MIMEMultipart() message['From'] = sender message['To'] = receiver message['Subject'] = subject
然后,我们需要添加邮件正文和附件:
# 添加邮件正文
body = 'This email contains an attachment.'
message.attach(MIMEText(body, 'plain'))
# 添加附件
with open('attachment.txt', 'rb') as file:
attach = MIMEApplication(file.read(), _subtype="txt")
attach.add_header('Content-Disposition','attachment',filename='attachment.txt')
message.attach(attach)
在上面的代码中,我们首先创建了一个包含邮件正文和附件的邮件对象message。然后,我们使用MIMEText类将邮件正文添加到邮件对象中,使用MIMEApplication类将附件添加到邮件对象中。
最后,我们需要连接到SMTP服务器,并发送邮件:
# 连接到SMTP服务器 smtp_server = 'smtp.example.com' port = 587 username = 'your_username' password = 'your_password' server = smtplib.SMTP(smtp_server, port) server.starttls() server.login(username, password) # 发送邮件 server.send_message(message) server.quit()
在上面的代码中,我们首先连接到SMTP服务器,并启用TLS加密。然后,我们使用login方法登录到SMTP服务器。最后,我们使用send_message方法发送邮件,并使用quit方法关闭服务器连接。
这就是使用Python的email.mime.multipart模块发送带附件的邮件的示例代码。你可以根据自己的需求修改代码中的相关信息,例如发送者、接收者、主题和附件的文件名等。
