python實現(xiàn)發(fā)送郵件及附件功能
今天給大伙說說python發(fā)送郵件,官方的多余的話自己去百度好了,還有一大堆文檔說實話不到萬不得已的時候一般人都不會去看,回歸主題:
本人是mac如果沒有按照依賴模塊的請按照下面的截圖安裝
導(dǎo)入模塊如果沒有錯誤,表示已經(jīng)安裝成功。
Python發(fā)送一個未知MIME類型的文件附件其基本思路如下:
1. 構(gòu)造MIMEMultipart對象做為根容器
2. 構(gòu)造MIMEText對象做為郵件顯示內(nèi)容并附加到根容器
3. 構(gòu)造MIMEBase對象做為文件附件內(nèi)容并附加到根容器
a. 讀入文件內(nèi)容并格式化
b. 設(shè)置附件頭
4. 設(shè)置根容器屬性
5. 得到格式化后的完整文本
6. 用smtp發(fā)送郵件
實例代碼:
#!/usr/bin/env python # -*- coding:utf-8 -*- import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication class Mailer(object): def __init__(self,maillist,mailtitle,mailcontent): self.mail_list = maillist self.mail_title = mailtitle self.mail_content = mailcontent self.mail_host = "smtp.163.com" self.mail_user = "your email name" self.mail_pass = "your email password" self.mail_postfix = "163.com" def sendMail(self): me = self.mail_user + "<" + self.mail_user + "@" + self.mail_postfix + ">" msg = MIMEMultipart() msg['Subject'] = 'Python mail Test' msg['From'] = me msg['To'] = ";".join(self.mail_list) #puretext = MIMEText('<h1>你好,<br/>'+self.mail_content+'</h1>','html','utf-8') puretext = MIMEText('純文本內(nèi)容'+self.mail_content) msg.attach(puretext) # jpg類型的附件 jpgpart = MIMEApplication(open('/home/mypan/1949777163775279642.jpg', 'rb').read()) jpgpart.add_header('Content-Disposition', 'attachment', filename='beauty.jpg') msg.attach(jpgpart) # 首先是xlsx類型的附件 #xlsxpart = MIMEApplication(open('test.xlsx', 'rb').read()) #xlsxpart.add_header('Content-Disposition', 'attachment', filename='test.xlsx') #msg.attach(xlsxpart) # mp3類型的附件 #mp3part = MIMEApplication(open('kenny.mp3', 'rb').read()) #mp3part.add_header('Content-Disposition', 'attachment', filename='benny.mp3') #msg.attach(mp3part) # pdf類型附件 #part = MIMEApplication(open('foo.pdf', 'rb').read()) #part.add_header('Content-Disposition', 'attachment', filename="foo.pdf") #msg.attach(part) try: s = smtplib.SMTP() #創(chuàng)建郵件服務(wù)器對象 s.connect(self.mail_host) #連接到指定的smtp服務(wù)器。參數(shù)分別表示smpt主機和端口 s.login(self.mail_user, self.mail_pass) #登錄到你郵箱 s.sendmail(me, self.mail_list, msg.as_string()) #發(fā)送內(nèi)容 s.close() return True except Exception, e: print str(e) return False if __name__ == '__main__': #send list mailto_list = ["aaa@lsh123.com","bbb@163.com"] mail_title = 'Hey subject' mail_content = 'Hey this is content' mm = Mailer(mailto_list,mail_title,mail_content) res = mm.sendMail() print res
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python實現(xiàn)超市商品銷售管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了python實現(xiàn)超市商品銷售管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-10-10Django 開發(fā)環(huán)境與生產(chǎn)環(huán)境的區(qū)分詳解
這篇文章主要介紹了Django 開發(fā)環(huán)境與生產(chǎn)環(huán)境的區(qū)分詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07python3的url編碼和解碼,自定義gbk、utf-8的例子
今天小編就為大家分享一篇python3的url編碼和解碼,自定義gbk、utf-8的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08