#! /usr/bin/python3
from email import encoders
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import os
import smtplib
import sys
import getopt
opts, args = getopt.getopt(sys.argv[1:], "hqa:s:t:c:")
file = ""
title = 'linux的通知'
content = ""
command = ''
debuglevel = 1
for op, value in opts:
if op == "-a":
file = value
elif op == "-s":
title = value
elif op == "-t":
content = value
elif op == "-c":
command = value
elif op == "-q":
debuglevel = 0
elif op == "-h":
print("-a :附件", 'q :靜音', 's :title', 'c 內容中的命令輸出', 't : 文本')
content = content + os.popen(command).read()
# 郵件對象:
msg = MIMEMultipart()
msg['From'] = ('【大王】')
msg['To'] = ('管理員')
msg['Subject'] = Header(title, 'utf-8').encode()
# 郵件正文是MIMEText:
msg.attach(MIMEText(content, 'plain', 'utf-8'))
# 添加附件就是加上一個MIMEBase,從本地讀取一個圖片:
if (os.path.isfile(file)):
with open(file, 'rb') as f:
# 設置附件的MIME和文件名,這裏是png類型:
mime = MIMEBase(MIMEText, os.path.splitext(file)[1], filename=os.path.basename(file))
# 加上必要的頭信息:
mime.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file))
mime.add_header('Content-ID', '<0>')
mime.add_header('X-Attachment-Id', '0')
# 把附件的內容讀進來:
mime.set_payload(f.read())
# 用Base64編碼:
encoders.encode_base64(mime)
# 添加到MIMEMultipart:
msg.attach(mime)
if (title != 'linux的通知' or content != '' or file != ''):
server = smtplib.SMTP('smtp.qq.com', 25) # SMTP協議默認端口是25
server.set_debuglevel(int(debuglevel))
server.login('[email protected]', 'lin1120')
server.sendmail('[email protected]', ['[email protected]'], msg.as_string())
server.quit()
自己用着很好,其實根本不用寫什麼shell腳本。python腳本完全可跑。有os.popen()等神器。以前學習過一個argparse模塊,真是太年輕,上面那個模塊又簡單有好用。哎~~~