Loading... <div class="tip share">请注意,本文编写于 1778 天前,最后修改于 1778 天前,其中某些信息可能已经过时。</div> 1、邮件发送 mailsend.py ``` #_*_ coding:utf-8 _*_ import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText class Sendmail: local_hostname = ['xxxx'] msg = MIMEMultipart('related') def __init__(self,smtp_server,mail_user,mail_pass): self.smtp_server = smtp_server self.mail_user = mail_user self.mail_pass = mail_pass def mess(self,theme,message): Sendmail.msg['Subject'] = theme # 邮件主题 html_msg = ''' <html><head><body> <p>%s</p> </body></head></html> ''' % message html = MIMEText(html_msg, 'html', 'utf-8') Sendmail.msg.attach(html) def files(self,path=None,filenames=None): if path == None and filenames == None: pass else: files = path + filenames att = MIMEText(open(files, 'rb').read(), 'base64', 'utf-8') att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'p_w_upload; filename=%s' % filenames Sendmail.msg.attach(att) def send(self,receiver): smtp = smtplib.SMTP() smtp.connect(self.smtp_server) smtp.ehlo(self.local_hostname) # 使用ehlo指令向smtp服务器确认身份 smtp.starttls() # smtp连接传输加密 smtp.login(self.mail_user, self.mail_pass) smtp.sendmail(self.mail_user, receiver, Sendmail.msg.as_string()) smtp.quit() if __name__ == "__main__": pass ``` 2、python flask web框架实现一个http接口 ``` #!/usr/bin/env python #_*_ coding:utf-8 _*_ from flask import Flask,request import json from mailsend import Sendmail app = Flask(__name__) @app.route('/sendmail' , methods=['GET', 'POST']) def index(): if request.method == 'POST': jsondata = request.get_data() data = json.loads(jsondata) s,e,f,r= data['smtpserver'],data['emailsubject'],data['filepath'],data['receivesuser'] email = Sendmail(s['server'],s['mailuser'],s['mailpasswd']) email.mess(e['subject'],e['mess']) email.files(f['path'],f['files']) print '邮件正在发送...' email.send(r['receiver']) return '邮件发送成功' else: return '<h1>只接受post请求!</h1>' if __name__ =='__main__': app.run(debug=True,host='0.0.0.0') ``` 3、调用这个接口发送邮件(不管是什么语言调用这个http接口,只要是传送json数据格式即可) ``` #_*_ coding:utf-8 _*_ #POST方式发送邮件数据到smtp http转发接口 import urllib2 import json def http_post(): url = 'http://192.168.89.8:5000/sendmail' data = {'smtpserver': {'server': 'mail.xxxxx.com', 'mailuser': 'txxtixnrxn@xrxdp.com', 'mailpasswd': '1qaz#EDC'}, 'emailsubject': {'subject': '这次测试做的很晚', 'mess': '现在好困'}, 'filepath': {'path': '/etc/', 'files': 'passwd'}, 'receivesuser': {'receiver': '23456723@qq.com'}} headers = {'Content-Type': 'application/json'} req = urllib2.Request(url=url, headers=headers, data=json.dumps(data)) response = urllib2.urlopen(req) return response.read() resp = http_post() print resp ``` 最后修改:2020 年 02 月 13 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果觉得我的文章对你有用,请随意赞赏