python3.5 email实现发送邮件功能

yipeiwu_com6年前Python基础

本文实例为大家分享了python3.5 email发送邮件的具体代码,供大家参考,具体内容如下

直接套用代码即可

from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email import encoders
import smtplib
import time


def send_mail(subject):
 email_host = '' # 服务器地址
 sender = '' # 发件人
 password = '' # 密码,如果是授权码就填授权码
 receiver = '' # 收件人

 msg = MIMEMultipart()
 msg['Subject'] = subject # 标题
 msg['From'] = '' # 发件人昵称
 msg['To'] = '' # 收件人昵称

 signature = '''
\n\t this is auto test report!
\n\t you don't need to follow
'''
 # text = MIMEText(signature, 'plain') # 签名
 # msg.attach(text)

 # 正文-图片 只能通过html格式来放图片,所以要注释25,26行
 mail_msg = '''
<p>\n\t this is auto test report!</p>
<p>\n\t you don't need to follow</p>
<p><a href="http://blog.csdn.net/wjoxoxoxxx" rel="external nofollow" >我的博客:</a></p>
<p>截图如下:</p>
<p><img src="cid:image1"></p>
'''
 msg.attach(MIMEText(mail_msg, 'html', 'utf-8'))
 # 指定图片为当前目录
 fp = open(r'111.jpg', 'rb')
 msgImage = MIMEImage(fp.read())
 fp.close()
 # 定义图片 ID,在 HTML 文本中引用
 msgImage.add_header('Content-ID', '<image1>')
 msg.attach(msgImage)

 ctype = 'application/octet-stream'
 maintype, subtype = ctype.split('/', 1)
 # 附件-图片
 image = MIMEImage(open(r'111.jpg', 'rb').read(), _subtype=subtype)
 image.add_header('Content-Disposition', 'attachment', filename='img.jpg')
 msg.attach(image)
 # 附件-文件
 file = MIMEBase(maintype, subtype)
 file.set_payload(open(r'320k.txt', 'rb').read())
 file.add_header('Content-Disposition', 'attachment', filename='test.txt')
 encoders.encode_base64(file)
 msg.attach(file)

 # 发送
 smtp = smtplib.SMTP()
 smtp.connect(email_host, 25)
 smtp.login(sender, password)
 smtp.sendmail(sender, receiver, msg.as_string())
 smtp.quit()
 print('success')

if __name_- == '__main__':
 now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
 subject = now + '自动化测试报告'
 send_mail(subject)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python获取全国城市pm2.5、臭氧等空气质量过程解析

随着国家发展,中国很多城市的空气质量其实并不好,国家气象局会有实时统计,但是要去写爬虫爬取是十分麻烦的事情,并且官方网站也会做一些反爬虫措施,所以实现起来比较麻烦,最好的办法就是使用现成...

pandas中的DataFrame按指定顺序输出所有列的方法

问题: 输出新建的DataFrame对象时,DataFrame中各列的显示顺序和DataFrame定义中的顺序不一致。 例如: import pandas as pd grades...

python 根据pid杀死相应进程的方法

用python语言实现根据pid杀死相应进程 kill_process.py代码如下 #! /usr/bin/python # -*- coding: utf-8 -*- impo...

Numpy中对向量、矩阵的使用详解

在下面的代码里面,我们利用numpy和scipy做了很多工作,每一行都有注释,讲解了对应的向量/矩阵操作。 归纳一下,下面的代码主要做了这些事: 创建一个向量 创建一个矩阵...

详谈Pandas中iloc和loc以及ix的区别

Pandas库中有iloc和loc以及ix可以用来索引数据,抽取数据。但是方法一多也容易造成混淆。下面将一一来结合代码说清其中的区别。 1. iloc和loc的区别: iloc主要使用数...