使用email.MIMEBase模块发送带有附件的邮件
发布时间:2023-12-14 03:26:50
email.MIMEBase模块是Python标准库中的一个模块,用于创建和处理MIME多媒体邮件(Multipurpose Internet Mail Extensions)。
下面是一个使用email.MIMEBase模块发送带有附件的邮件的例子:
import smtplib
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
def send_email_with_attachment(sender_email, sender_password, receiver_email, subject, message, attachment_path):
# 创建一个MIMEMultipart对象来构建邮件
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject
# 添加邮件正文
msg.attach(MIMEText(message, 'plain'))
# 读取附件文件并添加到邮件中
attachment = open(attachment_path, "rb")
#MIMEBase参数为传送的附件类型,application/octet-stream代表二进制流的形式传输
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read()) # 将附件文件内容读取并设置为payload
encoders.encode_base64(part) # 使用Base64编码附件
part.add_header('Content-Disposition', "attachment; filename= %s" % os.path.basename(attachment_path)) # 设置附件的名称
msg.attach(part) # 将附件添加到邮件中
# 使用SMTP协议登录邮箱服务器并发送邮件
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, sender_password)
text = msg.as_string() # 将MIMEMultipart对象转换成字符串
server.sendmail(sender_email, receiver_email, text)
server.quit()
# 发送邮件的参数设置
sender_email = "your_email@gmail.com" # 发件人邮箱
sender_password = "your_password" # 发件人邮箱密码
receiver_email = "recipient_email@gmail.com" # 收件人邮箱
subject = "Test Email with Attachment" # 邮件主题
message = "This is a test email with attachment." # 邮件正文
attachment_path = "path_to_attachment_file" # 附件文件路径
# 发送带有附件的邮件
send_email_with_attachment(sender_email, sender_password, receiver_email, subject, message, attachment_path)
在上面的例子中,我们首先导入了所需要的模块,创建了一个MIMEMultipart对象来构建邮件。然后,我们将邮件的发送者、接收者和主题等信息设置进去。接下来,我们添加了邮件的正文内容,然后读取附件文件并添加到邮件中。最后,我们使用SMTP协议登录邮箱服务器,并将MIMEMultipart对象转换成字符串后发送邮件。
请注意,这个例子中使用了Gmail的SMTP服务器,你需要将sender_email和sender_password替换成你自己的Gmail邮箱和密码,并将receiver_email替换成接收邮件的邮箱地址。同时,你需要将attachment_path替换成附件文件的实际路径。
希望这个例子能帮助到你理解如何使用email.MIMEBase模块发送带有附件的邮件。
