首页 > 代码库 > python之用smtplib模块使用第三方smtp发送邮件(通过flask实现一个http接口)
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 = ‘xxxxxx@xxxx.com‘ 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 = [‘xxxxxx@urundp.com‘,‘xxxx9@qq.com‘,‘xxxxx4@139.com‘] 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=xxxxx@qq.com,emailsub,message
本文出自 “FA&IT运维-Q群:223843163” 博客,请务必保留此出处http://freshair.blog.51cto.com/8272891/1874915
python之用smtplib模块使用第三方smtp发送邮件(通过flask实现一个http接口)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。