#!/usr/bin/python # -*- coding: UTF-8 -*- import flask, json from flask import request import smtplib from email.mime.text import MIMEText from email.utils import formataddr ''' flask: web框架,通过flask提供的装饰器@server.route()将普通函数转换为服务 登录接口,需要传url、username、passwd ''' # 创建一个服务,把当前这个python文件当做一个服务 server = flask.Flask(__name__) # server.config['JSON_AS_ASCII'] = False # @server.route()可以将普通函数转变为服务 登录接口的路径、请求方式 @server.route('/email', methods=['get', 'post']) def login(): # 获取通过url请求传参的数据 msg = request.values.get('msg') # 获取url请求传的密码,明文 address = request.values.get('address') # 判断用户名、密码都不为空,如果不传用户名、密码则username和pwd为None if msg and address: resu = {'code': 200, 'message': '登录成功'} ret=mail(address,msg) if ret: print("邮件发送成功") else: print("邮件发送失败") return json.dumps(resu, ensure_ascii=False) # 将字典转换为json串, json是字符串 else: resu = {'code': 10001, 'message': '参数不能为空!'} return json.dumps(resu, ensure_ascii=False) #sendmail函数 my_sender= 'FROM_MAIL' # 发件人邮箱账号aaaaaaaaaaa@qq.com my_pass = 'FROM_PASS' # 发件人邮箱密码ycxlplrdfkzjjiie my_user='TO_MAIL' # 收件人邮箱账号,我这边发送给自己bbbbbbb@163.com def mail(TO,MESSAGE): ret=True try: sendmsg=MIMEText(MESSAGE) sendmsg['From']=formataddr(["kafka",my_sender]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号 sendmsg['To']=formataddr(["FK",TO]) # 括号里的对应收件人邮箱昵称、收件人邮箱账号 sendmsg['Subject']="kafka报警服务" # 邮件的主题,也可以说是标题 server=smtplib.SMTP_SSL("MAIL_SERVER", 465) # smtp.qq.com发件人邮箱中的SMTP服务器,端口是25 server.login(my_sender, my_pass) # 括号中对应的是发件人邮箱账号、邮箱密码 server.sendmail(my_sender,[my_user,],sendmsg.as_string()) # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件 server.quit() # 关闭连接 except Exception: # 如果 try 中的语句没有执行,则会执行下面的 ret=False ret=False return ret # ret=mail() # if ret: # print("邮件发送成功") # else: # print("邮件发送失败") if __name__ == '__main__': server.run(debug=True, port=8888, host='0.0.0.0')# 指定端口、host,0.0.0.0代表不管几个网卡,任何ip都可以访问
dockerfile
FROM python:3.8.5-slim ENV FROM_MAIL='' FROM_PASS='' TO_MAIL='' MAIL_SERVER='' WORKDIR /mail COPY mail.py docker-entrypoint.sh /mail/ RUN chmod 755 /mail/docker-entrypoint.sh ENTRYPOINT ["/mail/docker-entrypoint.sh"] #必须要写成中括号的格式,要不然会被解析成bash -c ,这个ENTRYPOINT脚本的CMD参数就没起用 CMD ["python","/mail/mail.py"]
docker-entrypoint.sh
#!/bin/bash set -e pip install flask sed -i "s/FROM_MAIL/$FROM_MAIL/" /mail/mail.py sed -i "s/FROM_PASS/$FROM_PASS/" /mail/mail.py sed -i "s/TO_MAIL/$TO_MAIL/" /mail/mail.py sed -i "s/MAIL_SERVER/$MAIL_SERVER/" /mail/mail.py exec "$@"
http://192.168.1.131:8888/email?address=xiaoming&msg=woyaoni #触发请求地址接口