正文
廢話不多說(shuō),直接上代碼。
一、普通文本郵件(作通知訓(xùn)練結(jié)束用 :smiley: )
# -*- coding: UTF-8 -*- import smtplib from email.mime.text import MIMEText # 第三方 SMTP 服務(wù) mail_host = "smtp.163.com" # SMTP服務(wù)器 mail_user = "yourname" # 用戶名 mail_pass = "xxx" # 密碼(這里的密碼不是登錄郵箱密碼,而是授權(quán)碼) sender = 'yourname@163.com' # 發(fā)件人郵箱 receivers = 'othername@163.com'] # 接收人郵箱 content = 'Python Send Mail ! 訓(xùn)練結(jié)束!' title = 'Python SMTP Mail 訓(xùn)練結(jié)束' # 郵件主題 message = MIMEText(content, 'plain', 'utf-8') # 內(nèi)容, 格式, 編碼 message['From'] = "{}".format(sender) message['To'] = ",".join(receivers) message['Subject'] = title try: smtpObj = smtplib.SMTP_SSL(mail_host, 465) # 啟用SSL發(fā)信, 端口一般是465 smtpObj.login(mail_user, mail_pass) # 登錄驗(yàn)證 smtpObj.sendmail(sender, receivers, message.as_string()) # 發(fā)送 print("mail has been send to {0} successfully.".format(receivers)) except smtplib.SMTPException as e: print(e)
二、加強(qiáng)版附件傳輸郵件
# -*- 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' # 收郵件的地址,可以多個(gè)。 Receivers = ['receiver1@163.com','receiver2@163.com'] # 郵件主題: title = 'Python SMTP 郵件(文件傳輸)' # 模擬服務(wù)器 # SMTP服務(wù)器 SMTPServer="smtp.163.com" # 發(fā)郵件的地址 Sender="yourname@163.com" # 發(fā)送者郵件的授權(quán)密碼,去163郵箱設(shè)置里獲取。并非是密碼。 passwd="xxx" # 創(chuàng)建一個(gè)帶附件的實(shí)例 message = MIMEMultipart() message['From'] = Sender message['To'] = ",".join(Receivers) message['Subject'] = title # 郵件正文內(nèi)容 message.attach(MIMEText('附件中是要傳輸?shù)奈募?。\n ', 'plain', 'utf-8')) message.attach(MIMEText('The files you need are as followed. \n ', 'plain', 'utf-8')) # 構(gòu)造附件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) # 構(gòu)造附件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為端口號(hào)(郵件),0-1024都被系統(tǒng)占用了 # 登錄郵箱 mailServer.login(Sender, passwd) # 需要的是,郵箱的地址和授權(quán)密碼 # 發(fā)送文件 mailServer.sendmail(Sender, Receivers, message.as_string()) print("郵件發(fā)送成功") print("Mail with {0} & {1} has been send to {2} successfully.".format(file1,file2,Receivers)) except smtplib.SMTPException as e: print("Error: 無(wú)法發(fā)送郵件") print(e)
后話
可以把代碼加到網(wǎng)絡(luò)train.py的最后,別忘了在train.py的開(kāi)頭加上:
# -*- coding: UTF-8 -*- import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header
然后你就可以專(zhuān)心忙自己的事情,網(wǎng)絡(luò)訓(xùn)練結(jié)束就自動(dòng)發(fā)郵件啦~