Python发送信息及附件到邮箱

import smtplib
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email import encoders

#邮件格式
user = '[email protected]' #用户名
pwd = 'qfgezkkwzuiegcfh'   #密码
#发送到多个地址
Tolist=['[email protected]','[email protected]']
#To = '[email protected]'  选择单个目标地址
msg = MIMEMultipart()
msg['Subject'] = 'Letter of Death'
content1 = MIMEText('Fa♂Q!', 'plain', 'utf-8')

'''添加附件'''
msg.attach(content1)
#选择需要发送文件的位置
#发送文本信息
attfile = 'G://TestDemo//venv//网络爬虫学习//test.txt'  
#发送图片附件
attPic = 'G://TestDemo//venv\网络爬虫学习//at2.jpg'
attP1 = 'G://TestDemo//venv\网络爬虫学习//01.png'
attP2 = 'G://TestDemo//venv\网络爬虫学习//02.PNG'
basename = os.path.basename(attfile)
picname = os.path.basename(attPic)
p1name = os.path.basename(attP1)
p2name = os.path.basename(attP2)
#读取文件
fp = open(attfile, 'rb')
fp1 = open(attPic,'rb')
fp2 = open(attP1,'rb')
fp3 = open(attP2,'rb')
#发送附件
att = MIMEText(fp.read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att.add_header('Content-Disposition', 'attachment',filename=('gbk', '', basename))
encoders.encode_base64(att)
msg.attach(att)
#发送文件格式
attP1 = MIMEText(fp2.read(),'base64','utf-8')
attP1["Content-Type"] = 'application/octet-stream'
attP1.add_header('Content-Disposition', 'attachment',filename=('gbk', '', p1name))
encoders.encode_base64(attP1)
msg.attach(attP1)
#发送图片
att1 = MIMEText(fp1.read(),'base64','utf-8')
att1["Content-Type"] = 'application/octet-stream'
att1.add_header('Content-Disposition', 'attachment',filename=('gbk', '', picname))
encoders.encode_base64(att1)
msg.attach(att1)

attP2 = MIMEText(fp3.read(),'base64','utf-8')
attP2["Content-Type"] = 'application/octet-stream'
attP2.add_header('Content-Disposition', 'attachment',filename=('gbk', '', p2name))
encoders.encode_base64(attP2)
msg.attach(attP2)
#---------------------服务器配置----------------------------
s = smtplib.SMTP('smtp.qq.com')
s.login(user, pwd)  #登陆
s.sendmail(user, To, msg.as_string())
print('发送成功')
s.close()

猜你喜欢

转载自blog.csdn.net/qq_37504771/article/details/82558230