python之-郵件發送

Python之-郵件發送

模塊使用

  1. smtplib模塊
  2. time模塊 (用於時間延遲)
  3. email模塊中 header,mime(text,multipart)的使用

header : 用於定義mail頭部信息
mime.text : 用於定義郵件正文文本功能
mime.multipart : 用於定義郵件附件功能

#!/usr/bin/python3
#coding:utf-8

import smtplib
from time import sleep
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

class mailScript(object):
    
    def __init__(self,smtpServer, sender, password, receiver):
        self.smtpServer = smtpServer
        self.sender = sender 
        self.password = password
        self.receiver = receiver
        
    def mailAction(self):
        for num in range(1,101):
            mail_title = '測試%s' %num
            message = MIMEMultipart()
            message['From'] = self.sender
            message['To'] = self.receiver
            message['Subject'] = Header(mail_title, 'utf-8')
        
            message.attach(MIMEText('Virus test.', 'plain', 'utf-8'))
            virus = MIMEText(open('./sample_1028/'\
                                  +str(num)+'', 'rb').read(), 'base64', 'utf-8')
            virus["Content-Type"] = 'application/octet-stream'
            virus["Content-Disposition"] = \
                    'attachment; filename="test%s"' %(num)
            message.attach(virus)

            try:
                smtp = smtplib.SMTP()   # 創建一個連接
                smtp.connect(self.smtpServer)
                smtp.login(self.sender, self.password)
                #smtp.login(username, password)
                smtp.sendmail(self.sender, self.receiver, \
                              message.as_string())  # 填入郵件的相關信息併發送
                sleep(15)
                print("郵件發送成功!!!")
                smtp.quit()
            #except smtplib.SMTPException, e:
            except BaseExcetion, e:
                print("郵件發送失敗!!!")
                print(e)

    def _help(self):
        strings = "有的註釋是有特殊意義的\
                並非註釋比如qq的方式就需要輸入\
                username屬性根據自己需求定。"
        #username = '294****@qq.com'
        """這是qq的"""
        #mail_body = 'Virus test.'
        # 創建一個實例
        """發送正文只包含簡單文本的郵件,引入MIMEText即可"""
        #message = MIMEText(mail_body, 'plain', 'utf-8')
        """上面那個是發送正文啊文本之類的\
                mail_body屬性定義的就是內容"""
        print(strings)
   
if __name__=="__main__":
    sender = 'j******@163.com'
    receiver = 't****@f****.com'
    smtpServer = 'smtp.163.com'
    password = '*****'
    mail = mailScript(smtpServer, sender, password, receiver)
    #這裏的密碼不是賬戶密碼而是授權碼smtp
    mail.mailAction()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章