Python中如何使用email.mime.base模块的MIMEBase()函数发送带有附件的邮件
发布时间:2023-12-28 00:13:02
在Python中,我们可以使用email.mime.base模块的MIMEBase()函数来发送带有附件的邮件。下面是一个完整的使用示例。
首先,导入需要的模块:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email import encoders
接下来,准备发送邮件所需的内容:
from_addr = 'sender@example.com' # 发件人邮箱 to_addrs = ['receiver1@example.com', 'receiver2@example.com'] # 收件人邮箱,可以是一个列表 subject = '带附件的邮件' # 邮件主题 body = '这是一封带附件的邮件,请查收!' # 邮件正文 attachment_file = 'path/to/attachment_file.txt' # 附件文件路径
创建一个MIMEMultipart对象作为邮件容器,并设置相关属性:
msg = MIMEMultipart() msg['From'] = from_addr msg['To'] = ', '.join(to_addrs) msg['Subject'] = subject
将邮件正文添加到MIMEMultipart对象中:
msg.attach(MIMEText(body, 'plain'))
通过使用MIMEBase()函数创建一个表示附件的MIMEBase对象,并设置相关属性:
with open(attachment_file, 'rb') as f:
mime = MIMEBase('application', 'octet-stream')
mime.set_payload(f.read())
encoders.encode_base64(mime)
mime.add_header('Content-Disposition', 'attachment', filename=attachment_file.split('/')[-1])
msg.attach(mime)
连接SMTP服务器并发送邮件:
smtp_server = 'smtp.example.com' # SMTP服务器地址
username = 'sender@example.com' # 发件人邮箱用户名
password = 'password' # 发件人邮箱密码
try:
server = smtplib.SMTP(smtp_server)
server.starttls()
server.login(username, password)
server.send_message(msg)
print('邮件发送成功!')
except Exception as e:
print('邮件发送失败!错误信息:', str(e))
finally:
server.quit()
完整的示例代码如下:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from_addr = 'sender@example.com' # 发件人邮箱
to_addrs = ['receiver1@example.com', 'receiver2@example.com'] # 收件人邮箱,可以是一个列表
subject = '带附件的邮件' # 邮件主题
body = '这是一封带附件的邮件,请查收!' # 邮件正文
attachment_file = 'path/to/attachment_file.txt' # 附件文件路径
msg = MIMEMultipart()
msg['From'] = from_addr
msg['To'] = ', '.join(to_addrs)
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
with open(attachment_file, 'rb') as f:
mime = MIMEBase('application', 'octet-stream')
mime.set_payload(f.read())
encoders.encode_base64(mime)
mime.add_header('Content-Disposition', 'attachment', filename=attachment_file.split('/')[-1])
msg.attach(mime)
smtp_server = 'smtp.example.com' # SMTP服务器地址
username = 'sender@example.com' # 发件人邮箱用户名
password = 'password' # 发件人邮箱密码
try:
server = smtplib.SMTP(smtp_server)
server.starttls()
server.login(username, password)
server.send_message(msg)
print('邮件发送成功!')
except Exception as e:
print('邮件发送失败!错误信息:', str(e))
finally:
server.quit()
将上述示例代码中的发件人邮箱、收件人邮箱、附件文件路径、SMTP服务器地址、发件人邮箱用户名以及发件人邮箱密码替换为实际的信息,并运行代码,即可发送带有附件的邮件。
