1、开通SMTP和POP3协议
SMTP协议:发送邮件的协议(通过发送短信获取授权码)
POP3协议:接受邮件的协议
2、代码实现
import os
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from app import Base_dir
class EmailMange:
def send_email(self):
# 定义SMTP服务器
smtp_server = 'smtp.qq.com'
# 发送邮件的用户名和和客户端密码
username = '1165837644@qq.com'
password = 'cdzkjztpzpbfjeag' # 授权密码
# 接受邮件的邮箱
receiver = 'lebron_james0623@163.com'
# 创建邮件对象
message = MIMEMultipart('related')
subject = '平台模块准入测试结果'
# 邮件发送html内容
html_data = open('../report/index.html', 'rb+')
fujian = MIMEText(html_data.read(), 'html', 'utf-8')
html_data.close()
# fujian['Content-Disposition'] = 'attachment;filename="test1111.html"'
# 邮件发送xls文件
# fujian = MIMEText(open('../configure/test.xlsx', 'rb').read(), 'base64', 'utf-8')
# # # 设置文件在附件当中的名字
# fujian['Content-Disposition'] = 'attachment;filename="test1111.xlsx"'
# 发送图片
# rb 读取二进制文件
# 要确定当前目录有1.jpg这个文件
# image_data = open('../configure/test.jpg', 'rb')
# 设置读取获取的二进制数据
# fujian = MIMEImage(image_data.read())
# 关闭刚才打开的文件
# image_data.close()
# fujian.add_header('Content-ID', 'big')
# 添加图片文件到邮件信息当中去
# 把邮件的信息组装到邮件对象中
message['From'] = username
message['To'] = receiver
message['subject'] = subject
message.attach(fujian)
# 登录smtp服务器并发送邮件
smtp = smtplib.SMTP()
smtp.connect(smtp_server)
smtp.login(username, password)
smtp.sendmail(username, receiver, message.as_string())
smtp.quit()
if __name__ == '__main__':
EmailMange().send_email()