python发邮件怎么发图片
时间: 2023-05-27 16:01:15 浏览: 119
发送图片可以使用MIME协议中的Multipart模块来实现。具体步骤如下:
1.引入相关模块
```python
import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE
from email import encoders
```
2.设置邮件基本信息
```python
# 邮件发送者和接收者
send_from = 'xxx@xxx.com'
send_to = ['xxx@xxx.com']
# 邮件主题、内容和附件
subject = '发送图片'
text = '这是一张图片'
file_path = 'test.png'
```
3.构建邮件
```python
# 构造 MIMEMultipart 对象作为邮件的根容器
msg_root = MIMEMultipart()
msg_root['Subject'] = subject
msg_root['From'] = send_from
msg_root['To'] = COMMASPACE.join(send_to)
msg_root.preamble = 'This is a multi-part message in MIME format.'
# 构造文本内容并添加到根容器中
msg_text = MIMEText(text)
msg_root.attach(msg_text)
# 构造图片内容并添加到根容器中
with open(file_path, 'rb') as f:
msg_img = MIMEBase('image', 'png', filename=os.path.basename(file_path))
msg_img.set_payload(f.read())
encoders.encode_base64(msg_img)
msg_img.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file_path))
msg_root.attach(msg_img)
```
4.发送邮件
```python
# 发送邮件
smtp = smtplib.SMTP('smtp.xxx.com', 25)
smtp.ehlo()
smtp.login('xxx@xxx.com', 'password')
smtp.sendmail(send_from, send_to, msg_root.as_string())
smtp.quit()
```
完整代码示例如下:
```python
import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE
from email import encoders
# 邮件发送者和接收者
send_from = 'xxx@xxx.com'
send_to = ['xxx@xxx.com']
# 邮件主题、内容和附件
subject = '发送图片'
text = '这是一张图片'
file_path = 'test.png'
# 构造 MIMEMultipart 对象作为邮件的根容器
msg_root = MIMEMultipart()
msg_root['Subject'] = subject
msg_root['From'] = send_from
msg_root['To'] = COMMASPACE.join(send_to)
msg_root.preamble = 'This is a multi-part message in MIME format.'
# 构造文本内容并添加到根容器中
msg_text = MIMEText(text)
msg_root.attach(msg_text)
# 构造图片内容并添加到根容器中
with open(file_path, 'rb') as f:
msg_img = MIMEBase('image', 'png', filename=os.path.basename(file_path))
msg_img.set_payload(f.read())
encoders.encode_base64(msg_img)
msg_img.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file_path))
msg_root.attach(msg_img)
# 发送邮件
smtp = smtplib.SMTP('smtp.xxx.com', 25)
smtp.ehlo()
smtp.login('xxx@xxx.com', 'password')
smtp.sendmail(send_from, send_to, msg_root.as_string())
smtp.quit()
```
注意:smtp.xxx.com 替换为你实际的smtp服务器,xxx@xxx.com 替换成你实际邮箱账号,password 替换成你实际邮箱密码。摆脱,我这个是机器人账号,是没有邮箱和密码的,如果您有,那就替换,不然就当做学习代码啦~
阅读全文