這篇文章主要為大家詳細介紹了python實現發送郵件及附件功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下
今天給大夥說說python發送郵件,官方的多餘的話自己去百度好了,還有一大堆文檔說實話不到萬不得已的時候一般人都不會去看,回歸主題:
本人是mac如果沒有按照依賴模組的請按照下面的截圖安裝
#導入模組如果沒有錯誤,表示已經安裝成功。
Python發送一個未知MIME類型的檔案附件其基本想法如下:
1. 建構MIMEMultipart物件做為根容器
2. 建構MIMEText物件做為郵件顯示內容並附加到根容器
3. 建構MIMEBase物件做為文件附件內容並附加到根容器
a. 讀入文件內容並格式化
b. 設定附件頭
4. 設定根容器屬性
5. 得到格式化後的完整文字
6. 用smtp傳送郵件
實例程式碼:
#!/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('纯文本内容'+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() #创建邮件服务器对象 s.connect(self.mail_host) #连接到指定的smtp服务器。参数分别表示smpt主机和端口 s.login(self.mail_user, self.mail_pass) #登录到你邮箱 s.sendmail(me, self.mail_list, msg.as_string()) #发送内容 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
以上是python中如何實現發送郵件及附件功能的具體詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!