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

在Python中使用MIMEBase()发送带图片附件的邮件

发布时间:2024-01-17 01:27:35

在Python中使用MIMEBase()发送带图片附件的邮件可以通过以下步骤实现:

1. 导入必要的模块:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
from email import encoders

2. 创建MIMEMultipart对象作为邮件容器,并设置发件人、收件人、主题等基本信息:

msg = MIMEMultipart()
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
msg['Subject'] = '带图片附件的邮件'

3. 添加邮件内容,可以是纯文本或者HTML格式:

body = MIMEText('这是一封带图片附件的邮件', 'plain')
msg.attach(body)

4. 添加图片附件:

with open('path/to/image.jpg', 'rb') as f:
    image = MIMEImage(f.read())
    image.add_header('Content-Disposition', 'attachment', filename='image.jpg')
    msg.attach(image)

- 使用with open('path/to/image.jpg', 'rb') as f:打开要发送的图片文件;

- 使用MIMEImage(f.read())读取图片内容,并创建一个MIMEImage对象;

- 使用image.add_header('Content-Disposition', 'attachment', filename='image.jpg')给MIMEImage对象添加一个Content-Disposition头部,设置附件的文件名;

- 使用msg.attach(image)将MIMEImage对象添加到MIMEMultipart对象中。

5. 发送邮件:

server = smtplib.SMTP('smtp.example.com', 25)
server.login('username', 'password')
server.send_message(msg)
server.quit()

- 创建一个SMTP对象,并连接到SMTP服务器;

- 使用server.login('username', 'password')登录到SMTP服务器;

- 使用server.send_message(msg)发送邮件;

- 使用server.quit()关闭连接。

完整的示例代码如下:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
from email import encoders

msg = MIMEMultipart()
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
msg['Subject'] = '带图片附件的邮件'

body = MIMEText('这是一封带图片附件的邮件', 'plain')
msg.attach(body)

with open('path/to/image.jpg', 'rb') as f:
    image = MIMEImage(f.read())
    image.add_header('Content-Disposition', 'attachment', filename='image.jpg')
    msg.attach(image)

server = smtplib.SMTP('smtp.example.com', 25)
server.login('username', 'password')
server.send_message(msg)
server.quit()

注意事项:

- 需要提供正确的SMTP服务器地址和端口号;

- 需要提供发件人和收件人的邮箱地址;

- 需要提供SMTP服务器的登录用户名和密码;

- 需要提供正确的图片文件路径。