python smtplib
时间: 2023-11-03 07:59:51 浏览: 165
Python的smtplib模块提供了一种简单的方法来发送邮件。首先,您需要创建一个SMTP对象,然后使用sendmail方法发送邮件。如果要发送带有图片的邮件,您可以使用email模块中的MIMEMultipart和MIMEImage类来创建带附件的实例。以下是一个示例代码:
```
import smtplib
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
sender = 'bmjoker@163.com'
passwd = 'xxxxxxxx'
receivers = '19xxxxxx9@qq.com'
subject = 'python发邮带img的邮件测试' #主题
# 创建一个带附件的实例
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receivers
# 创建正文
msg.attach(MIMEText('使用python smtplib模块和email模块自动发送邮件测试','plain','utf-8'))
# 创建图片附件
import os
img_file = open(os.getcwd() "/a4.jpg",'rb').read()
msg_img = MIMEImage(img_file)
msg_img.add_header('Content-Disposition','attachment', filename = "a4.jpg")
msg_img.add_header('Content-ID', '<0>')
msg.attach(msg_img)
try:
s = smtplib.SMTP('smtp.163.com',25)
s.set_debuglevel(1) #输出发送邮件详细过程
s.login(sender,passwd)
s.sendmail(sender,receivers,msg.as_string())
print('Send Succese')
except:
print('Send Failure')
```
阅读全文