发送邮件

一.获取授权码

1.QQ邮箱设置->账户

2.开启服务:POP3/SMTP点开启

3.按照提示发送短信

4.复制授权码

代码:
 mail.py
#coding:utf-8
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart  #上面的MIMEText只能发送正文,无法带附件,发送带附件的需要导入另外一个模块MIMEMultipart
 
#参数配置
smtpserver="smtp.qq.com"#发送服务器
port=465 #端口
sender="455572224@qq.com"#发件人邮箱
psw="xxxxxxxxx"#授权码
receiver="455572224@qq.com"#收件人邮箱,如果与多个收件人可以用list receiver=["xxxx@qq.com","xxxxx@qq.com"]
 
#读取文件
file_path="result.html"  #不在同一个脚本夹文件下的话,需要用绝对路径("D:\\xxx\\xx\\result.html","r")
with open(file_path,"rb")as fp:
  mail_body=fp.read()
 
#定义一个容器
msg=MIMEMultipart() #这是一个混合型的模版
 
#配置发件人、收件人主题
msg["from"]=sender #msg是一个字典对象
msg["to"]=receiver #如果多个收件人,不要为list,只能是字符串msg=["to"]='xxxx@qq.com","xxxxx@qq.com"'或者"msg["to"]=";".join(receiver) 用分号;隔开,也可使用其他
msg["subject"]="主题,自行定义"
 
#正文
bd="<pre><h1>测试报告,请查收</h1></pre>"
#添加正文内容到容器
body=MIMEText(bd,"html","utf-8")
msg.attach(body)
 
#附件
#添加附件到容器
att=MIMEText(mail_body,"base64","utf-8")#base64是数据流格式,否则没法识别
#声明几个类型
att["Content-Type"]="application/octet-stream"
att["Content-Disposition"]='attachment;filename="result.html"'
msg.attach(att)
 
# #-**-读取附件内容到正文上-**-
# body=MIMEText(mail_file,"html","utf-8")
# msg.attach(body)
 
#发送邮件(两种)
#发送流程SSL,授权码登录
smtp=smtplib.SMTP_SSL(smtpserver,port)#调用smtplib模块里SMTP_SSL的类,SSL是加密协议,将发件服务器和端口传进去,这一步是实例化
smtp.login(sender,psw)#调用login传入发件人,授权码
smtp.sendmail(sender,receiver,msg.as_string())
smtp.quit()
 
# #有些邮箱是可以直接登录的
# smtp=smtplib.SMTP()
# smtp.connect(smtpserver,port)#链接服务
# smtp.login(sender,psw)
# smtp.sendmail(sender,receiver,msg.as_string())
# smtp.quit()
 
#如何自动识别哪种发送方式可用如下两种方法:if...else... 或 try...except...
#发送邮件
# def send_email(sender,psw,is_psw=True):
# if is_psw:#如果是密码登录的
# #有些邮箱是可以直接登录的
# smtp=smtplib.SMTP()
# smtp.conncet(smtpserver,port)
# smtp.login(sender,psw)
# smtp.sendmail(sender,receiver,msg.as_string())
# smtp.quit()
# else:
# smtp=smtplib.SMTP_SSL(smtpserver,port)
# smtp.login(sender,psw)
# smtp.sendmail(sender,receiver,msg.as_string())
# smtp.quit()

try:
#连接服务器
smtp=smtplib.SMTP()
smtp.conncet(smtpserver,port)
smtp.login(sender,psw)
except:
#登录
smtp=smtplib.SMTP_SSL(smtpserver,port)
smtp.login(sender,psw)
#发送
smtp.sendmail(sender,receiver,msg.as_string())
#关闭
smtp.quit()
posted @ 2017-10-25 10:09  女林  阅读(240)  评论(0编辑  收藏  举报