1. 程式人生 > >Python傳送郵件模組(SMTP)

Python傳送郵件模組(SMTP)

首先,使用SMTP實現傳送郵件的話,需要先獲取一個代發郵件的授權碼。

以163郵箱為例:

登入郵箱後--點選設定--客戶端授權碼--開啟。如圖

其實網上已經有很多類似的模組介紹和試用了,這邊主要是想記錄下自己寫的一個類。呼叫方式簡單,可以直接將py檔案貼到專案中,import後直接呼叫,方便快捷,簡單高效。

# coding=utf-8
import sys, os, fileinput, smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


reload(sys)
sys.setdefaultencoding('utf-8')


class EmailUtils:
    def __init__(self, mailto_list, email_title, email_content):
        self.mailto_list = mailto_list
        self.email_title = email_title
        self.email_content = email_content

    # 傳送郵件
    def send_mail(self):
        # 設定伺服器名稱、使用者名稱、密碼以及郵件字尾
        mail_host = 'smtp.163.com'
        mail_user = '
[email protected]
' # 郵箱地址 mail_pass = 'xxxxxxxx' # 即授權碼 # mailto_list = ['[email protected]'] me = mail_user msg = MIMEMultipart() msg['Subject'] = self.email_title msg['From'] = me msg['To'] = ",".join(self.mailto_list) # html = '''<!DOCTYPE html>dddd</html>''' context = MIMEText(self.email_content, _subtype='html', _charset='utf-8') # 解決亂碼 msg.attach(context) send_smtp = smtplib.SMTP() send_smtp.connect(mail_host) send_smtp.login(mail_user, mail_pass) send_smtp.sendmail(me, self.mailto_list, msg.as_string()) send_smtp.close() if __name__ == '__main__': mail_content = """""" mail_content += "APP名稱:" + "\n" mail_content += "編譯時間" + "\n" mail_content += "編譯版本" + "\n" mail_content += "測試時間" + "\n" mail_content += "\n" # 讀取一個檔案 file_input_stream = fileinput.input(os.getCwd() + "\\testResult\\result.log") for line in file_input_stream: mail_content += line + "\n" EmailUtil.send_mail(['
[email protected]
','[email protected]','[email protected]'], "test", mail_content)