python之用smtplib模块使用第三方smtp发送邮件(通过flask实现一个http接口)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python之用smtplib模块使用第三方smtp发送邮件(通过flask实现一个http接口)相关的知识,希望对你有一定的参考价值。
1、邮件发送
#!/usr/bin/env python #coding:utf-8 import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def email_send(recipient,theme,message,path=None,filenames=None): local_hostname = [‘toby-ThinkPad-T430shhhh‘] msg = MIMEMultipart(‘related‘) #第三方smtp服务器 smtp_server = ‘mxxx.xxxxp.com‘ mail_user = ‘[email protected]‘ mail_pass = ‘xxxxxx‘ #发件人和收件人 sender = ‘xxxxxx‘ #发件人 receiver = recipient#收件人 msg[‘Subject‘] = theme #邮件主题 #纯文本格式内容 #text = MIMEText(‘这是纯文本内容‘, ‘plain‘, ‘utf-8‘) #msg.attach(text) #html内容 html_msg = ‘‘‘ <html><head><body> <p>%s</p> </body></head></html> ‘‘‘ % message html = MIMEText(html_msg,‘html‘,‘utf-8‘) msg.attach(html) #构造附件 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"] = ‘attachment; filename=%s‘ % filenames msg.attach(att) #发送邮件 try: smtp = smtplib.SMTP() smtp.connect(smtp_server) smtp.ehlo(local_hostname) #使用ehlo指令向smtp服务器确认身份 smtp.starttls() #smtp连接传输加密 smtp.login(mail_user, mail_pass) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit() return True except smtplib.SMTPException,ex: print ex ‘‘‘ if __name__ == "__main__": #接口格式: 收件人、主题、消息,[路径,附件] theme = ‘这是一封测试邮件‘ message = ‘测试邮件,请查阅,谢谢!‘ to_mail = [‘[email protected]‘,‘[email protected]‘,‘[email protected]‘] if email_send(to_mail,theme,message) == True: print ‘邮件发送成功‘ else: print ‘邮件发送失败‘ ‘‘‘
2、flask
#!/usr/bin/env python #_*_ coding:utf-8 _*_ from flask import Flask, request from mail import email_send app = Flask(__name__) @app.route(‘/‘) def index(): email = request.args.get(‘email‘) data = email.split(‘,‘) if email_send(data[0],data[1],data[2],data[3]=None,data[4]=None) == True: print ‘邮件发送成功‘ else: print ‘邮件发送失败‘ return ‘<h1>%s</h1>‘ % email if __name__ == "__main__": app.run(debug=True) #发送格式 http://127.0.0.1:5000/[email protected],emailsub,message
本文出自 “FA&IT运维-Q群:223843163” 博客,请务必保留此出处http://freshair.blog.51cto.com/8272891/1874915
以上是关于python之用smtplib模块使用第三方smtp发送邮件(通过flask实现一个http接口)的主要内容,如果未能解决你的问题,请参考以下文章
python模块----yagmail模块smtplib模块 (电子邮件)