搭建Http接口
from flask import Flask
from flask import request
from email.mime.text import MIMEText
import smtplib
app = Flask(__name__)
app.debug = True
@app.route('/')
def hello_world():
return 'Hello World123!'
# request.form:用于接收表单参数
# request.data: 获取传参
# request.args:用于接收GET参数
# request.json:用于接收JSON参数
# request.values:获取所有参数(表单参数+GET参数)
# request.file:用于接收文件
@app.route("/sendmail", methods=['POST'])
def send_mail():
# 获取邮件内容
content = request.data.decode()
print(content)
# 设置服务器所需信息
# qq邮箱服务器地址
mail_host = 'smtp.qq.com'
# qq用户名
mail_user = 'zhuzhiqianghao'
# 密码(部分邮箱为授权码)
mail_pass = 'bbbaziqavbxtcaie'
# 邮件发送方邮箱地址
sender = 'zhuzhiqianghao@qq.com'
# 邮件接受方邮箱地址,注意需要[]包裹,这意味着你可以写多个邮件地址群发
receivers = ['zhu_zhiqiang@dahuatech.com', 'song_gongde@dahuatech.com', 'zhuzhiqiangxx@163.com']
# 设置email信息
# 邮件内容设置
message = MIMEText(content, 'plain', 'utf-8')
# 邮件主题
message['Subject'] = '停车云报警'
# 发送方信息
message['From'] = sender
# 接受方信息
message['To'] = ','.join(receivers)
# 登录并发送邮件
try:
smtpObj = smtplib.SMTP()
# 连接到服务器
smtpObj.connect(mail_host, 25)
# 登录到服务器
smtpObj.login(mail_user, mail_pass)
# 发送
smtpObj.sendmail(sender, receivers, message.as_string())
# 退出
smtpObj.quit()
print('success')
return "send success"
except smtplib.SMTPException as e:
print('error', e) # 打印错误
return "send fail"
return 'send mail success'
if __name__ == '__main__':
app.run(debug=True,port=8001)
测试接口
import requests
import json
data = {'key1':'value1','key2':'value2'}
url = "http://127.0.0.1:5000/sendmail"
r = requests.post(url, data=json.dumps(data))
print(r)
通过shell 发送邮件
curl -H "Content-Type: application/json"
-X POST
-d '{"user_id": "123", "coin":100, "success":1, "msg":"OK!" }'
"http://127.0.0.1:5000/sendmail"
网友评论