import smtplib
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email import encoders
# 邮件格式
user = 'xxx@xx.com' # 邮箱用户名
pwd = '...' # 密码
# 发送到多个地址
Tolist=['xxx@qq.com','xxx@qq.com']
#To = 'xxx@163.com' # 选择单个目标地址
msg = MIMEMultipart()
msg['Subject'] = 'Python邮箱'
# 文本格式
content1 = MIMEText('Fa♂Q!', 'plain', 'utf-8')
'''添加附件'''
msg.attach(content1)
# 选择需要发送文件的位置
# 发送文本信息
attfile = 'G://TestDemo//venv//网络爬虫学习//test.txt'
# 发送图片附件
attPic = '图片路径'
attP1 = '...'
attP2 = '...'
# 创建读取文件对象
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()
Python发送信息及附件到邮箱
最新推荐文章于 2022-08-14 14:35:34 发布