由於純文本的郵件內容已經不能滿足多樣化的需求,主要介紹通過引入mail.mime的MIMEText 類來實現支持HTML格式的郵件,支持所有HTML格式的元素,包括表格,圖片,動畫,css樣式,表單等。(參考劉老師文獻)
案例中收集的是最簡單的服務器硬件信息,通過smtp將信息發到收件人郵箱,大家可以根據自己的需求收集所需要的信息(比如CPU百分比,硬盤剩餘百分比,內存使用百分比,並設定閾值,當硬盤剩餘空間不足10%,發送郵件通知管理員及時處理)
#!/usr/bin/env python
#coding: utf-8
import smtplib
import os
import psutil
from email.mime.text import MIMEText //導入MIMEText類
ip = os.popen("ifconfig |grep -v 127 |grep inet |awk '{print $2}'|cut -d: -f2").read().strip() //獲取IP地址
hostname = os.popen("hostname").read().strip() //獲取主機名
cpu = psutil.cpu_count() //獲取CPU線程
mem = os.popen("free -m |grep Mem |awk '{print $2}'").read().strip()+"M" //獲取內存總量
disk = os.popen("fdisk -l |grep -E Disk |awk '{print $3}'").read().strip()+"G" //獲取硬盤總大小
HOST = "smtp.163.com" //指定使用網易163郵箱
SUBJECT = u"服務器硬件信息" //郵件標題
TO = "[email protected]" //收件人
FROM = "[email protected]" //發件人
msg = MIMEText("""
<table color="CCCC33" width="800" border="1" cellspacing="0" cellpadding="5" text-align="center">
<tr>
<td text-align="center">name</td>
<td text-align="center">network</td>
<td>CPU</td>
<td>Mem</td>
<td>Disk</td>
</tr>
<tr>
<td text-align="center">%s </td>
<td>%s </td>
<td>%s </td>
<td>%s </td>
<td>%s </td>
</tr>
</table>""" % (hostname,ip,cpu,mem,disk),"HTML","uft-8")
msg['Subject'] = SUBJECT
msg['From'] = FROM
msg['To'] = TO
try:
server = smtplib.SMTP() //創建一個SMTP對象
server.connect(HOST,"25") //通過connect方法鏈接到smtp主機
server.starttls() //啓動安全傳輸模式
server.login("[email protected]","passwordxx") // 登錄163郵箱 校驗用戶,密碼
server.sendmail(FROM, [TO], msg.as_string()) //發送郵件
server.quit()
print "郵件發送成功 %s %s %s %s %s" % (hostname,ip,cpu,mem,disk) /發送成功並打印
except Exception, e:
print "郵件發送失敗:"+str(e)
運行結果:
大家可以收集自己需要的信息,通過判斷服務器的狀態信息,併發相關信息郵件。