yagmail 实现发邮件
安装
pip install yagmail
简单例子
import yagmail
args = {
"user":"szm254310****@163.com", #邮箱
"password":"*****999", #第三方登录授权码
"host":"smtp.163.com", #服务器
"port":"465" #端口
}
contects='''
DT:SPM 是出错信息的关键词
'''
email = yagmail.SMTP(**args)
#to 代表接受方(可以是list(推送给多个人)) subject 主题 contents内容
email.send(to="25431****@qq.com",subject="原因分享1",contents=contects)
image.png
SMTP 发送邮箱
通过python发邮件步骤:
前提是:开通了第三方授权,可以使用smtp服务
- 创建一个smtp对象
- 连接smp服务器,默认端口都是25
- 登录自己邮箱账号,
- 调用发送消息函数,参数:发件人,收件人,消息内容
- 关闭连接
smtp = smtplib.SMTP()
smtp.connect('smtp.163.com', '25')
smtp.login('18910****69@163.com', 'ling***15')
smtp.sendmail('1891***469@163.com', '97**44081@qq.com', msg.as_string())
smtp.quit()
邮件消息注册:
首先创建一个消息对象:
msg = email.mime.multipart.MIMEMultipart()
msg['from'] = '18***9@163.com'
msg['to'] = '97***81@qq.com;141***73@qq.com;li***ing@jd.com'
msg['subject'] = 'ajing1111‘
分别指明邮件的发件人,收件, 只代表显示的问题
消息内容:
首先,先定义一个字符串,来表示你得消息内容:
context= ‘’’hello world’’’
txt = email.mime.text.MIMEText(_text=content, _subtype="html")
msg.attach(txt)
_subtype这个参数就决定了,你是以html解析的形式去发送,还是以text的形式去发送。
简单例子
import email.mime.multipart
import email.mime.text
import smtplib
msg = email.mime.multipart.MIMEMultipart()
msg['from']='*****@163.com'
msg['to'] ='*****@qq.com'
msg['subject'] ='邮件分享'
context = '''
<h1>老师<h1>
<span>帅气</span>
'''
text = email.mime.text.MIMEText(_text=context,_subtype="html")
msg.attach(text)
em = smtplib.SMTP_SSL()
em.connect("smtp.163.com",465)
em.login("szm******5@163.com","*****9")
em.sendmail(from_addr="*****@163.com",to_addrs="****5@qq.com",msg=msg.as_string())
em.quit()
发送附件:
1,先找一个本地的文件
2,打开文件,读出文件字符串
3,通过MIMT ext()类来创建一个对象att,传入文件读出内容
4,增加att的头部信息,并指定文件名字
5,添加到msg消息中msg.attach(att)
attfile = 'test.py'
basename = os.path.basename(attfile)
fp = open(attfile, 'rb')
att = email.mime.text.MIMEText(fp.read(), 'html', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att.add_header('Content-Disposition', 'attachment',filename=('utf-8', '', basename))#three-tuple of (charset, language, value),
# encoders.encode_base64(att)
msg.attach(att)
发送图片:
1,本地必须存在一张图片;
2,打开图片,并读取图片内容
3,创建发邮件相对应的图片对象imgattr = MIMEImage(fimg.read())
4,增加图片的头信息, imgattr.add_header('Content-ID', '<image1>')
指定了图片的id,图片如果想在正文中显示,必须通过html的格式显示出来:在前端代码中指定图片id
6,<img src = 'cid:image1'>
7,添加到message的信息中