如何在Python中使用email.MIMEMultipartMIMEMultipart()发送带附件的邮件
发布时间:2024-01-07 23:10:31
在Python中,我们可以使用email和smtplib库来发送带附件的邮件。MIMEMultipart类是email库中的一个类,它允许我们创建包含多个部分的邮件。
一、导入必要的库
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication
二、创建MIMEMultipart对象
使用MIMEMultipart类创建一个带附件的邮件对象,可以通过添加多个部分来构建邮件的内容。
msg = MIMEMultipart()
三、设置邮件的主题、发件人、收件人以及正文内容
msg['Subject'] = '带附件的邮件'
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
msg.attach(MIMEText('这是邮件的正文内容', 'plain'))
四、添加附件
附件可以是文本文件、图片等。我们需要将文件内容转换为MIMEApplication类型,并设置文件的名称和类型。
with open('path/to/attachment.txt', 'rb') as f:
attachment = MIMEApplication(f.read())
attachment['Content-Disposition'] = 'attachment; filename="attachment.txt"'
msg.attach(attachment)
五、发送邮件
通过smtplib库发送邮件。
server = smtplib.SMTP('smtp.example.com', 587) # 以SMTP服务器地址和端口号连接
server.starttls() # 启用TLS加密
server.login('sender@example.com', 'password') # 登录发件人邮箱
server.send_message(msg) # 发送邮件
server.quit() # 断开连接
完整的代码示例:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
msg = MIMEMultipart()
msg['Subject'] = '带附件的邮件'
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
msg.attach(MIMEText('这是邮件的正文内容', 'plain'))
with open('path/to/attachment.txt', 'rb') as f:
attachment = MIMEApplication(f.read())
attachment['Content-Disposition'] = 'attachment; filename="attachment.txt"'
msg.attach(attachment)
server = smtplib.SMTP('smtp.example.com', 587)
server.starttls()
server.login('sender@example.com', 'password')
server.send_message(msg)
server.quit()
以上就是使用email.MIMEMultipart类发送带附件的邮件的方法。我们可以根据需要修改邮件的主题、发件人、收件人、正文内容以及附件信息。
