python利用poplib发送邮件,嵌入图片
时间: 2023-03-29 12:00:55 浏览: 167
可以使用email和smtplib库来发送带有图片的邮件,具体实现可以参考以下代码:
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.header import Header
# 邮件服务器地址和端口号
smtp_server = 'smtp.example.com'
smtp_port = 25
# 发件人邮箱和密码
sender = 'sender@example.com'
password = 'password'
# 收件人邮箱
receiver = 'receiver@example.com'
# 创建一个带有图片的邮件
msg = MIMEMultipart()
msg['From'] = Header('发件人姓名', 'utf-8')
msg['To'] = Header('收件人姓名', 'utf-8')
msg['Subject'] = Header('邮件主题', 'utf-8')
# 邮件正文
text = MIMEText('邮件正文', 'plain', 'utf-8')
msg.attach(text)
# 图片附件
with open('image.jpg', 'rb') as f:
image = MIMEImage(f.read())
image.add_header('Content-ID', '<image1>')
msg.attach(image)
# 发送邮件
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.login(sender, password)
server.sendmail(sender, receiver, msg.as_string())
print('邮件发送成功')
except Exception as e:
print('邮件发送失败:', e)
finally:
server.quit()
```
其中,smtp_server和smtp_port需要根据你的邮件服务器进行修改,sender和password是发件人的邮箱和密码,receiver是收件人的邮箱,image.jpg是要嵌入的图片文件名。
阅读全文