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

使用Python的email.mime.multipart库发送带有视频附件的邮件

发布时间:2023-12-14 12:00:44

使用Python的email.mime.multipart库可以发送带有视频附件的邮件。下面是一个使用例子,包含了创建邮件、添加附件、设置邮件内容和发送邮件的步骤。

1. 导入必要的模块:

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

2. 创建一个带有附件的邮件:

msg = MIMEMultipart()
msg['From'] = 'sender@gmail.com'
msg['To'] = 'receiver@gmail.com'
msg['Subject'] = 'Video attachment'

# 附件文件路径
video_file = 'path_to_video_file.mp4'

# 以二进制模式打开附件文件
attachment = open(video_file, 'rb')

# 创建一个MIMEBase对象,并设置内容类型为'application/octet-stream'
video_part = MIMEBase('application', 'octet-stream')
video_part.set_payload((attachment).read())
encoders.encode_base64(video_part)

# 设置附件的标题(可以根据需要修改)
video_part.add_header('Content-Disposition', "attachment; filename= %s" % video_file.split('/')[-1])

# 将附件添加到邮件中
msg.attach(video_part)

3. 设置邮件内容:

body = "Please find the attached video."
msg.attach(MIMEText(body, 'plain'))

4. 发送邮件:

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

请确保替换示例代码中的发件人和收件人邮箱地址、附件文件路径以及发送邮件的SMTP服务器和登录凭据。