您的位置:首页 > 编程语言 > Python开发

Python自动发送邮件--smtplib模块

2020-01-12 17:12 441 查看
[code]import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.image import MIMEImage

account='9xxxx65@qq.com'  #发件人
pwd = '*******'    #第三方授权码,需登录qq mail web页,开通设置。
to = ['xxxxx@qq.com','xxxx@qq.com','xxxx@qq.com'] # 发送给多个收件人
host='smtp.qq.com'      #主机
atta_path = r'C:\Users\Administrator\Desktop\testdata.txt'  #附件路径与名称
name='要展示的文件名.txt'      #附件显示的名称
img_path = r'C:\Users\Administrator\Desktop\dog.jpg'    #显示在正文中的图片

# 这是正文显示部分,其中img标签中的src的cid:0,这个0与下文的content-ID对应。

content='''
<html><body><h3>
Project:</h3>  <p>mobile test</p>
<h3>Tester:</h3> <p>fish</p>
<h3>Date:</h3> <p>2019/12/12</p>
<h3>Result:</h3> <p>Pass</p>
<p>For morn details,you can check <a href= 'https://www.baidu.com'>Test Result</a></p>
<img src='cid:0' alt = 'picture'>
</body></html>
'''
def sendmail():

ret = True
try:
msg = MIMEMultipart()
msg['Subject'] = 'Test'
msg['From'] = account
msg['To'] = ';'.join(to)

#将图片显示在邮件正文中
fp=open(img_path,'rb')
img= MIMEImage(fp.read())
img.add_header('Content-ID', '0')
msg.attach(img)

#邮件中显示正文
part_text = MIMEText(content,'html','UTF-8')
msg.attach(part_text)

#这是附件部分,不同类型的附件,只需修改名称、位置、要显示的名字
part_att = MIMEApplication(open(atta_path,'rb').read())
part_att.add_header('Content-Disposition', 'attachment', filename=name)
msg.attach(part_att)

#实例化一个SMTP的对象,然后登录、发送邮件
s = smtplib.SMTP(host,timeout= 30)
s.login(account,pwd)
s.sendmail(account,to,msg.as_string())
s.close()
except Exception as e:
ret = False
resaon = str(e)
return ret

ret = sendmail()

if ret:
print('send successfully')
else:
print('Error: send failed: ',reason)

如上的代码,可实现一个简单的邮件自动发送,且不会显示在垃圾箱中。

  • 点赞
  • 收藏
  • 分享
  • 文章举报
李斌L 发布了41 篇原创文章 · 获赞 6 · 访问量 366 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: