正文
廢話不多說,直接上代碼。
一、普通文本郵件(作通知訓練結束用 :smiley: )
# -*- coding: UTF-8 -*- import smtplib from email.mime.text import MIMEText # 第三方 SMTP 服務 mail_host = "smtp.163.com" # SMTP服務器 mail_user = "yourname" # 用戶名 mail_pass = "xxx" # 密碼(這里的密碼不是登錄郵箱密碼,而是授權碼) sender = 'yourname@163.com' # 發件人郵箱 receivers = 'othername@163.com'] # 接收人郵箱 content = 'Python Send Mail ! 訓練結束!' title = 'Python SMTP Mail 訓練結束' # 郵件主題 message = MIMEText(content, 'plain', 'utf-8') # 內容, 格式, 編碼 message['From'] = "{}".format(sender) message['To'] = ",".join(receivers) message['Subject'] = title try: smtpObj = smtplib.SMTP_SSL(mail_host, 465) # 啟用SSL發信, 端口一般是465 smtpObj.login(mail_user, mail_pass) # 登錄驗證 smtpObj.sendmail(sender, receivers, message.as_string()) # 發送 print("mail has been send to {0} successfully.".format(receivers)) except smtplib.SMTPException as e: print(e)
二、加強版附件傳輸郵件
# -*- coding: UTF-8 -*- import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header # Files' Paths: file1 = 'mail.py' file2 = 'maill.py' # 收郵件的地址,可以多個。 Receivers = ['receiver1@163.com','receiver2@163.com'] # 郵件主題: title = 'Python SMTP 郵件(文件傳輸)' # 模擬服務器 # SMTP服務器 SMTPServer="smtp.163.com" # 發郵件的地址 Sender="yourname@163.com" # 發送者郵件的授權密碼,去163郵箱設置里獲取。并非是密碼。 passwd="xxx" # 創建一個帶附件的實例 message = MIMEMultipart() message['From'] = Sender message['To'] = ",".join(Receivers) message['Subject'] = title # 郵件正文內容 message.attach(MIMEText('附件中是要傳輸的文件。\n ', 'plain', 'utf-8')) message.attach(MIMEText('The files you need are as followed. \n ', 'plain', 'utf-8')) # 構造附件1 att1 = MIMEText(open(file1, 'rb').read(), 'base64', 'utf-8') att1["Content-Type"] = 'application/octet-stream' att1["Content-Disposition"] = 'attachment; filename={0}'.format(file1) message.attach(att1) # 構造附件2 att2 = MIMEText(open(file2, 'rb').read(), 'base64', 'utf-8') att2["Content-Type"] = 'application/octet-stream' att2["Content-Disposition"] = 'attachment; filename={0}'.format(file2) message.attach(att2) try: mailServer = smtplib.SMTP(SMTPServer, 25) # 25為端口號(郵件),0-1024都被系統占用了 # 登錄郵箱 mailServer.login(Sender, passwd) # 需要的是,郵箱的地址和授權密碼 # 發送文件 mailServer.sendmail(Sender, Receivers, message.as_string()) print("郵件發送成功") print("Mail with {0} & {1} has been send to {2} successfully.".format(file1,file2,Receivers)) except smtplib.SMTPException as e: print("Error: 無法發送郵件") print(e)
后話
可以把代碼加到網絡train.py的最后,別忘了在train.py的開頭加上:
# -*- coding: UTF-8 -*- import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header
然后你就可以專心忙自己的事情,網絡訓練結束就自動發郵件啦~