模拟发送邮件前,需要先开启SMTP服务
操作步骤为:打开邮箱,设置--账户--开启服务
(1)配置文件中配置如下信息
[email] sender = 发送者邮箱 sender_pwd = 授权码 receiver = 收件人邮箱 subject = 测试报告主题
(2)python自带的发送邮件功能
import smtplib from email.mime.multipart import MIMEMultipart # 附件 from email.mime.text import MIMEText # 邮件文本 from email.mime.application import MIMEApplication # 添加发送附件 from com.myconf import conf def send_email(file_path,file_name): # 第一步连接到smtp服务器 smtp=smtplib.SMTP_SSL("smtp.qq.com",465) smtp.login(conf.get('email','sender'),conf.get('email','sender_pwd')) # 第二步构建邮件 smg=MIMEMultipart() text_smg = MIMEText(open(file_path, 'r', encoding='utf8').read(), "html") # 邮件类型:html格式,plain是文本 smg.attach(text_smg) file_msg = MIMEApplication(open(file_path, "rb").read()) file_msg.add_header('content-disposition', 'attachment', filename=file_name) smg.attach(file_msg) smg["Subject"] = conf.get('email','subject') smg["From"] = conf.get('email','sender') smg["To"] = conf.get('email','receiver') # 第三步发送邮件 smtp.send_message(smg,from_addr=conf.get('email','sender'),to_addrs=conf.get('email','receiver')) if __name__ == '__main__': pass
(3)yagmail发送邮件
python的第三方库,需要先安装库
-
在线安装yagmail(如已安装,无需再安装)
python -m pip install yagmail
安装成功:
-
yagmail发送邮件
import os import yagmail from com.myconf import conf def send_mail(file_path,file_name): yag = yagmail.SMTP(user=conf.get('email','sender'), password=conf.get('email','sender_pwd'), host='smtp.qq.com') subject = conf.get('email','subject') # 发送邮件 report = os.path.join(file_path,file_name) yag.send(conf.get('email','sender'),conf.get('email','receiver'), report)
注意:给多接收者,发送多附件,用[]格式表示即可