python--发送邮件

一、zmial发送邮件

zmial是第三方库,需进行安装

>pip install zmail

完成后,来给发一封邮件

subject:标题
content_text:内容
1 import zmail
2 server = zmail.server('发件人邮箱地址','授权码')
3 
4 server.send_mail('收件人邮箱地址',{'subject':'Hello!','content_text':'By zmail.'})

 二、smtplib发送邮件

 1 import smtplib
 2 from email.mime.text import MIMEText
 3 #--------发件相关参数--------
 4 smtpserver="smtp.qq.com"    #连接服务器
 5 port = 465                      #端口
 6 sender = "741841851@qq.com"#账号
 7 psw = "xxxxx"#密码 授权码
 8 receiver="741841851@qq.com"#接收人
 9 
10 #--------编辑邮件内容--------
11 
12 subject="qq邮件主题"
13 body= '<p>这个是发送的qq邮件</p>'
14 msg = MIMEText(body,'html','utf-8')
15 msg['from']=sender
16 msg['to']='741841851@qq.com'
17 msg['subject']=subject
18 
19 #-----------test_email-------
20 smtp = smtplib.SMTP_SSL(smtpserver,port)#连接服务器
21 smtp.login(sender,psw)#登录
22 smtp.sendmail(sender,receiver,msg.as_string())#发送邮件
23 smtp.quit()

三、发送带附件的邮件

 

 1 import smtplib
 2 from email.mime.text import MIMEText
 3 from email.mime.multipart import MIMEMultipart
 4 import os
 5 
 6 smtpserver='smtp.qq.com'
 7 port =465
 8 sender='741841851@qq.com'
 9 psw = 'xxxx'
10 recevier = "741841851@qq.com"
11 
12 filenamepath = os.path.join(os.path.dirname(os.path.realpath(__file__)),'ceshi.html')
13 
14 with open(filenamepath,'rb') as f:
15     mail_body=f.read().decode('utf-8')
16 
17 msg = MIMEMultipart()
18 msg['from']=sender#发件人
19 msg['to']=recevier#收件人
20 msg['subject']='这是我的主题99'#主题
21 
22 # 正文
23 body = MIMEText(mail_body,'html','utf-8')
24 msg.attach(body)
25 #附件
26 att = MIMEText(mail_body,'base64','gbk')#用utf-8会出现乱码
27 att['Content-Type']='application/octet-stream'
28 att['Content-Disposition']='attachment;filename="test_report.html"'
29 msg.attach(att)
30 
31 ####发送邮件
32 try:
33     smtp = smtplib.SMTP()
34     smtp.connect(smtpserver)#连接服务器
35     smtp.login(sender,psw)#登录
36 except:
37     smtp = smtplib.SMTP_SSL(smtpserver,port)
38     smtp.login(sender,psw)#登录
39 
40 smtp.sendmail(sender,recevier,msg.as_string())#发送邮件
41 smtp.quit()

 

posted @ 2019-06-24 16:07  莫使娇躯空对月  阅读(283)  评论(0编辑  收藏  举报