最近为了加强服务器监管信息,于是为所有服务器配置邮件增设报警监测功能,LINUX服务器可以使用SHELL即可轻松解决,但是为了通用性(还有部分WINDOWS系统服务器),后来改为使用Python程序实现其功能。现将邮件部分代码分享其实现过程的简单思路:
The program supports sending multiple types of attachment messages: code below
#!/usr/bin/python
#coding: Utf-8
#author by Jerry 2017.1
Import Smtplib
From Email.mime.text import Mimetext
From Email.header Import Header
Import string
From Email.parser Import Parser
From Email.mime.multipart import Mimemultipart
From email.mime.application import mimeapplication
Host = "Baidu.com"
sender = "[Email protected]"
receivers = "[Email protected]"
User= "username"
authcode= "Password"
Mybody= "This is body content test."
Subject= "Jerry ' s Test"
Message=mimemultipart ()
# message body Add
Mybody = Mimetext ("Good,send Mail OK")
Message.attach (Mybody)
#---This is the attachment section---
Att1 =mimeapplication (Open (' IDC server Reports.xls ', ' RB '). Read (), _charset= ' Utf-8 ')
Att1.add_header (' content-disposition ', ' attachment ', filename= "IDC server Reports.xls")
Message.attach (ATT1)
Att1=mimeapplication (Open (' domain.txt ', ' RB '). Read ())
Att1.add_header (' content-disposition ', ' attachment ', filename= "Domain.txt")
Message.attach (ATT1)
Att1=mimeapplication (Open (' Test.rar ', ' RB '). Read ())
Att1.add_header (' content-disposition ', ' attachment ', filename= "Test.rar")
Message.attach (ATT1)
#整合
headers = Parser (). Parsestr (' from: [Email protected]\n '
' To: [email protected]\n '
' subject:%s '% Subject + ' \ n '
'%s '% message + ' \ n '
)
Try
Server = Smtplib. SMTP (host)
Server.login (User,authcode) #远程smtp主机方法. The quotes are account numbers and passwords.
Server.sendmail (sender,receivers,headers.as_string ())
Server.quit () #断开smtp服务器
Print ("Mail sent successfully")
Except Smtplib. Smtpexception as E:
Print (e)
Print ("Mail sendfail!")
Python program sends server status information alert mail (with multiple types of attachments)