【Python】利用python自動發送郵件
前言
在訓練網路的過程中,需要大量的時間,雖然可以預估網路訓練完成時間,但蹲點看結果著實有點不太聰明的亞子。
因此,參照師兄之前發的python利用smtp自動發郵件的程式碼,我作了些調整,並參照網上的開源程式碼,整理出了加強版(可以傳文件),這樣訓練的log還有model,或者是遠程電腦上的文件都可以通過郵件即時到達接收郵件的郵箱很方便吧~~
正文
廢話不多說,直接上程式碼。
一、普通文本郵件(作通知訓練結束用 😃 )
# -*- 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 = '[email protected]' # 發件人郵箱
receivers = ['[email protected]'] # 接收人郵箱
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 = ['[email protected]','[email protected]']
# 郵件主題:
title = 'Python SMTP 郵件(文件傳輸)'
# 模擬伺服器
# SMTP伺服器
SMTPServer="smtp.163.com"
# 發郵件的地址
Sender="[email protected]"
# 發送者郵件的授權密碼,去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
然後你就可以專心忙自己的事情,網路訓練結束就自動發郵件啦~
果然——Codes change the world. 😃