Python自动发送邮件-smtplib和email库
生活随笔
收集整理的這篇文章主要介紹了
Python自动发送邮件-smtplib和email库
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、先導入smtplib模塊 導入MIMEText庫用來做純文本的郵件模板
二、發郵件幾個相關的參數,每個郵箱的發件服務器不一樣,以163為例子百度搜索服務器是 smtp.163.com
三、寫郵件主題和正文,這里的正文是HTML格式的
四、最后調用SMTP發件服務
126mail -> qqmail send email
import uuid import smtplib from email.mime.text import MIMEText#發郵件相關參數 smtpsever = 'smtp.126.com' sender = '123@126.com' psw = "XXX" #126郵箱授權碼 receiver = '456@qq.com'#編輯郵件的內容 # subject=u"NBA" body=str(uuid.uuid4()) msg=MIMEText(body,'html','utf-8') msg['from']='123@126.com' msg['to']='456@qq.com' # msg['subject']=subjecttry:smtp = smtplib.SMTP()smtp.connect(smtpsever)smtp.login(sender,psw)smtp.sendmail(sender,receiver,msg.as_string())print ("郵件發送成功") except smtplib.SMTPException:print ("Error: 無法發送郵件")qqmail->126mail send email
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:778463939 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import smtplib,uuid from email.mime.text import MIMEText#發郵件相關參數 smtpsever='smtp.qq.com' sender='123@qq.com' psw="XXXXX" #qq郵箱授權碼 receiver='456@qq.com' port=465#編輯郵件內容 subject = u"你猜這是啥?" body = str(uuid.uuid4()) msg=MIMEText(body,'html','utf-8') msg['from']='123@qq.com' msg['to']='456@qq.com' msg['subject'] = subject#鏈接服務器發送 smtp = smtplib.SMTP_SSL(smtpsever,port) smtp.login(sender,psw) #登錄 smtp.sendmail(sender,receiver,msg.as_string()) #發送 smtp.quit() #關閉發送帶附件的郵件
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart#發郵件相關參數 smtpsever='smtp.qq.com' sender='123@qq.com' #psw="xxxx" #126郵箱授權碼 psw="xxxx" receiver='456789@qq.com' port=465filepath="E:\\result.html" #編輯郵件的內容 with open(filepath,'rb') as fp: #讀文件mail_body=fp.read()#主題 msg=MIMEMultipart() msg["from"]=sender msg["to"]=receiver msg["subject"]=u"這個我的主題"#正文 body=MIMEText(mail_body,"html","utf-8") msg.attach(body) att = MIMEText(mail_body,"base64","utf-8") att["Content-Type"] = "application/octet-stream" att["Content-Disposition"] = 'attachment; filename="test_report.html"' msg.attach(att)try:smtp=smtplib.SMTP()smtp.connect(smtpsever) #連接服務器smtp.login(sender,psw) except:smtp=smtplib.SMTP_SSL(smtpsever,port)smtp.login(sender,psw) #登錄 smtp.sendmail(sender,receiver,msg.as_string()) #發送 smtp.quit()總結
以上是生活随笔為你收集整理的Python自动发送邮件-smtplib和email库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python教程:列表推导式对比For循
- 下一篇: python文件读read()、read