python-发送正文并带附件邮件

发送带附件的邮件

案例:发送E:\Python_script\目录下 logo.png图片文件到指定的邮箱
import smtplib                                  #发送邮件模块
from email.mime.text import MIMEText            #定义邮件内容
from email.mime.multipart import MIMEMultipart  #用于传送附件

#发送邮箱服务器
smtpserver='smtp.163.com'

#发送邮箱用户名密码
user='[email protected]'
password='070337shu'

#发送和接收邮箱
sender='[email protected]'
receives=['[email protected]','[email protected]']


#发送邮件主题和内容
subject='Web Selenium 附件发送测试'


#'rb'表示r读取,b表示二进制方式读取
with open(r"E:\Python_script\logo.png",'rb') as f:
    mail_content=f.read()


#这是邮件正文内容
html=MIMEText(mail_content,'html','utf-8')


#构造附件内容:定义附件,构造附件内容
att=MIMEText(mail_content,'base64','utf-8')                  #调用传送附件模块,传送附件
att["Content-Type"]='application/octet-stream'
att["Content-Disposition"]='attachment;filename="logo.png"'  #附件描述外层要用单引号


#构建发送与接收信息
msgRoot=MIMEMultipart()                             #发送附件的方法定义为一个变量
msgRoot.attach(MIMEText(content, 'html', 'utf-8'))  #发送附件的方法中嵌套发送正文的方法
msgRoot['subject']=subject
msgRoot['From']=sender
msgRoot['To'] = ','.join(receives)

msgRoot.attach(att)                                 #添加附件到邮件中
msgRoot.attach(html)                                #添加报告正文到邮件正文中


#SSL协议端口号要使用465
smtp = smtplib.SMTP_SSL(smtpserver, 465)

#HELO 向服务器标识用户身份
smtp.helo(smtpserver)
#服务器返回结果确认
smtp.ehlo(smtpserver)
#登录邮箱服务器用户名和密码
smtp.login(user,password)

print("Start send email...")

smtp.sendmail(sender,receives,msgRoot.as_string())

smtp.quit()
print("Send End!")

你可能感兴趣的:(python-发送正文并带附件邮件)