之前有用過Linux自帶的mail工具來定時發送郵件,但是要裝mailx還有配mail.rc,這還比較正常,關鍵是到了ubantu下這工具用起來真是操蛋,如果哪天其他的unix like操作系統也有需求,那就太麻煩了,所以我用自帶的python2.6.6和自帶的郵件相關的庫寫了個小工具,使用步驟如下:
一、申請一個163郵箱,作為發件箱。
不用qq郵箱是因為,qq郵箱的SMTP服務器需要獨立的密碼,比較麻煩一點。
二、創建如下腳本,改名為SendMail.py:
注意將以下腳本中的from_addr和password改為你自己的163郵箱和密碼即可。
#!/usr/bin/python
# -*- coding: utf-8 -*-
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import os,sys
import smtplib
import getopt
#使用幫助
def usage():
print('''Usage:
SendMail.py [Options]
eg. SendMail.py -s "郵件標題" -c "郵件正文" -d "xxx@xxx.com,yyy@yyy.com" --content-file mail_content.txt --attach attachment.log
Options:
-h/--help 顯示此幫助
-s 郵件標題,例如: -s "這里是郵件標題"
-c 郵件正文,例如: -c "這里是郵件正文"
-d 郵件接收地址,例如: -d "xxx@xxx.com,yyy@yyy.com"
--content-file 包含郵件正文的文件,例如: --content-file mail_content.txt
--attach 附件,可以是絕對或相對路徑,例如: --attach attachment.log 或者 --attach /var/log/attachment.log
Ps:目前此腳本只支持一個附件,暫無發送多個附件的需求
''')
#參數解析
def argParse():
subject,content,destAddr,content_file,attachment=None,None,None,None,None
'''
如果參數很多,可以選擇用argparse模塊,argparse是更加完善、更加簡單的參數解析工具,這里用getopt只是因為想試下getopt怎么用。
getopt(args, shortopts, longopts = [])
shortopts表示短項參數,longopts表示長項參數,前者使用'-'后者使用'--',需要后接具體參數的短項參數后需要加冒號':'標識,longopts則必須以=結尾,賦值時寫不寫等號無所謂因為默認是模糊匹配的。
getopt的返回值分兩部分,第一部分是所有配置項和其值的list,類似[(opt1,val1),(opt2,val2),...],第二部分是未知的多余參數,我們只需要在第一部分的list取參數即可。
第二部分一般無需關注,因為我們會使用getopt.GetoptError直接過濾掉這些參數(即直接報option xxx not recognized)。
'''
try:
sopts, lopts = getopt.getopt(sys.argv[1:],"hs:c:d:",["help","content-file=","attach="])
except getopt.GetoptError as e:
print("GetoptError:")
print(e)
sys.exit(-1)
for opt,arg in sopts:
if opt == '-s':
subject=arg
elif opt == '-c':
content=arg
elif opt == '-d':
destAddr=arg
elif opt == '--attach':
attachment=arg
elif opt == '--content-file':
content_file=arg
elif opt == '--attach':
attachment=arg
else:
usage()
sys.exit(-1)
#subject,destAddr必須不能為空
if not subject or not destAddr:
usage()
print("Error: subject and destination must not be null!")
sys.exit(-1)
#處理正文文件,如果存在正文文件,那么忽略-c參數,以文件內容為郵件正文
if content_file and os.path.exists(content_file):
try:
with open(content_file) as f1:
content=f1.read()
except:
print("Can't open or read the content file!")
exit(-1)
else:
pass
return {'s':subject,'c':content,'d':destAddr,'a':attachment,}
#發送郵件
def main():
opts=argParse()
subject,content,dest,attach=opts['s'],opts['c'],opts['d'],opts['a']
#通用第三方smtp服務器賬號密碼
smtp_server = 'smtp.163.com'
from_addr = '你的163發件箱'
password = '你的163發件箱密碼'
to_addr = list(dest.split(","))
msg = MIMEMultipart()
msg['From'] = from_addr
msg['To'] = ','.join(to_addr)
msg['Subject'] = subject
msg.attach(MIMEText(content, 'plain', 'utf-8'))
#處理附件
if attach and os.path.exists(attach):
try:
with open(attach) as f2:
mime=f2.read()
#目前懶的再寫多個附件了,因此只支持一個附件
attach1=MIMEApplication(mime)
attach1.add_header('Content-Disposition','attachment',filename=attach)
msg.attach(attach1)
except:
print("Can't open or read the attach file!")
exit(-1)
else:
pass
server = smtplib.SMTP_SSL(smtp_server, 465) #如果使用的25端口的非加密通道,那么使用SMTP方法替換SMTP_SSL
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, to_addr, msg.as_string())
server.quit()
if __name__=='__main__':
main()
三、更改權限后就可以在安裝了python的服務器上發送郵件啦(一般服務器都自帶python2版本)。
例如:
[root@python leo]# chmod 755 SendMail.py [root@python leo]# ./SendMail.py -s "郵件標題" -c "郵件正文" -d "xxx@qq.com" --content-file mail.txt
