1.邮箱设置
IMAP/SMTP服务 开启
POP3/SMTP服务 开启
2.邮箱地址
POP3服务器: pop.163.com 用于接收
SMTP服务器: smtp.163.com 用于发送
IMAP服务器: imap.163.com 接收/发送
3.引入模块
import smtplib
# 引入发送内容模块
from email.mime.text import MIMEText
# 引入发送附件模块
from email.mime.multipart import MIMEMultipart
# 邮箱地址
mail_host = 'smtp.163.com'
# 用户名 邮箱
mail_user = '******@163.com'
# 密码 授权密码
mail_pass = '************'
# 设置发送邮箱
sender = '****@163.com'
# 接收邮件邮箱(要发送的人)
receivers = ['xxxx@qq.com']
# 设置文本
# massage = MIMEText('您好','plain','utf-8')
# MIMEMultipart 可传输附件,可传输文本
massage = MIMEMultipart()
massage['Subject'] = '每日报告'
massage['From'] = sender
massage['To'] = receivers[0]
content = MIMEText('请注意查看附件','plain','utf-8')
# 将文本加入massage
massage.attach(content)
with open('./tests/daily_report.pdf','rb') as f:
att = MIMEText(f.read(),'base64','utf-8')
att['Content-Type'] = 'application/octet-stream'
att['Content-Disposition'] = 'attachment;filename="daily_report.pdf"'
massage.attach(att)
try:
smtpObj = smtplib.SMTP_SSL(mail_host,465)
smtpObj.set_debuglevel(1)
smtpObj.login(mail_user,mail_pass)
smtpObj.sendmail(sender,receivers,massage.as_string())
smtpObj.quit()
print("邮件发送成功")
except Exception as e:
print('error',e)