前言:繼前篇zabbix郵件亂碼問題解決,轉碼後,問題是解決了,可是又發現問題,有時候告警郵件沒有郵件內容,只有標題,一直沒找出緣由,因此就換了Python腳本發送郵件,代碼以下。python
使用前固然是要先安裝python了,而後是導入相關的運行庫smtplib,python的smtplib提供了一種很方便的途徑發送電子郵件,它對smtp協議進行了簡單的封裝。app
#!/usr/bin/python #coding:utf-8 import smtplib from email.mime.text import MIMEText import sys # configure your own parameters here #下面郵件地址的smtp地址 mail_host = 'smtp.mail.qq.com' #用來發郵件的郵箱,在發件人擡頭顯示(否則你的郵件會被當成是垃圾郵件) mail_user = 'XXXX@qq.com' #上面郵箱的密碼 mail_pass = 'XXXX!' #上面smtp地址的主網站地址 mail_postfix = 'mail.qq.com' def send_mail(to_list,subject,content): me = mail_user+"<"+mail_user+"@"+mail_postfix+">" msg = MIMEText(content, 'plain', 'utf-8') # 必須使用'utf-8'參數,不然默認爲us-ascii, 在部分郵件客戶端中文會顯示爲亂碼 msg['Subject'] = subject msg['From'] = me msg['to'] = to_list try: s = smtplib.SMTP() s.connect(mail_host) s.login(mail_user,mail_pass) s.sendmail(me,to_list,msg.as_string()) s.close() return True except Exception,e: print str(e) return False if __name__ == "__main__": send_mail(sys.argv[1], sys.argv[2], sys.argv[3])
腳本主要就改4項:函數
#下面郵件地址的smtp地址
mail_host = 'smtp.mail.qq.com'
#用來發郵件的郵箱,在發件人擡頭顯示(否則你的郵件會被當成是垃圾郵件)
mail_user = 'XXX@qq.com'
#上面郵箱的密碼
mail_pass = 'XXXXX'
#上面smtp地址的主網站地址
mail_postfix = 'mail.qq.com'post
這個腳本須要輸入三個參數來測試:測試
第一個是要發送的郵件地址,優化
第二個是郵件標題,網站
第三個是郵件內容blog
python sendmail.py XXXX@qq.com title 'content'ip
收到郵件就完成了.utf-8
發送郵件改進:
支持發送多人,支持發送附件,代碼以下:
#!/usr/bin/python #coding:utf-8 # import smtplib import sys from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication from email.mime.text import MIMEText #配置你的郵箱信息 mail_host = 'smtp.mail.qq.com' mail_user = 'XXXX@qq.com' mail_pass = 'XXXX' mail_postfix = 'mail.qq.com' #發送郵件函數 def send_mail(to_list,subject,content,file_list): #採用related定義內嵌資源的郵件體 msg = MIMEMultipart('related') #郵件內容 msgtext = MIMEText(content, 'plain', 'utf-8') msg.attach(msgtext) #附件部分 for attachfile in file_list.split(','): attach = MIMEApplication(open(attachfile,'rb').read()) attach.add_header('Content-Disposition', 'attachment', filename=attachfile) msg.attach(attach) me = mail_user+"<"+mail_user+"@"+mail_postfix+">" msg['Subject'] = subject msg['From'] = me mail_to_list = to_list.split(',') msg['to'] = ','.join(mail_to_list) try: s = smtplib.SMTP() s.connect(mail_host) s.login(mail_user,mail_pass) s.sendmail(me,mail_to_list,msg.as_string()) s.close() return True except Exception,e: print "發送失敗"+str(e) return False if __name__ == "__main__": send_mail(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4])