標籤:python
1、郵件發送
#!/usr/bin/env python#coding:utf-8import 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, requestfrom mail import email_sendapp = 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>‘ % emailif __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介面)