Python script sends alert message

Source: Internet
Author: User
Tags mail code stdin python script

Recently in the Nagios alarm mailbox Exchange to 163, Sina this free mailbox top, before used msmtp can also send mail, now estimate is their system is upgraded, can only use TSL encrypted connection, and msmtp how configuration is not available, helpless can only transfer tactics, Just recently in the study of Python, do not know where to see the module has an email, so prepare to try to make a script.

(Novice, no programming basis, hope more advice)

#!/usr/bin/env python# -*- coding: utf-8 -*-# --2015.08.11--#  Scripts are used to replace Nagios monitoring using the # sendemail.py #  method:# printf  "Mail Content"  | sendemail.py -s   "Mail Subject"  -R  recipient 1, Recipient 2import smtplibimport sys,getoptfrom email.mime.text  Import mimetexttry:    opts, args = getopt.getopt (sys.argv[1:],  ' S:r: ')     subject =  '     receivers = []     for i in opts:        if  '-S '  in i:            subject = i[ 1]        elif  '-R '  in i:             receivers.append (i[1])          else:            print  "Please input parameters" except getopt. getopterror, e:    print ehost =  ' smtp.qq.com ' port =  465sender =  ' [email protected] ' copyto = [' [email protected] ']pass =  ' xxx ' #既然readlines读取为表格, then the table is broken into a pure string body =  '. Join (Sys.stdin.readlines ()) #以下代码段使用的MIMEText函数会生成邮件头格式, Provides some option configuration (Object.sendmail method) Msg = mimetext (body) msg[' subject '] = subjectmsg[' from ' When sending mail in the rear ] = sender# in the message header, the recipient or CC, the format should be "[email protected],[email protected]" instead of "[' [email  Protected] ',  ' [email protected] ' msg[' to '] =  ', '. Join (receivers) msg[' cc '] =  ', ' The. Join (CopyTo) #这里是接受者列表, not the recipient list, so includes the CC, sent to the recipient. #而具体是抄送还是密送交给MIMEText函数生成格式 (CC/BCC), and is used as a parameter by the Object.sendmail method receivers = receivers +  Copytos = smtplib. Smtp_ssl (Host, port) s.login (sender, pass) S.sendmail (Sender, receivers, msg.as_string ()) 

Script slightly messy I was roughly divided into three parts

The first section, setting variables such as sender recipient topic

The second part, using the Mimetext function to format the message content subject such as message header format

The third part, log in the mailbox, send the mail code

If you do not want to take it, you can change the sender (sender variable), sender SMTP (host variable), sender password (pass variable), cc person (copyto variable, our company fixed several people so I directly to the mailbox script, you can also be written as parameter designation)

List several problems encountered

1, do not understand what the mimetext is exactly what is it generated what kind of a mail header?


>>> from email.mime.text import MIMEText>>> body =  ' 123456 ' >>> subject =  ' test mail ' >>> sender =  ' [email  protected] '       >>> receivers =  ' [email  Protected] ' >>> copyto =  ' [email protected] ' >>> msg =  Mimetext (body) >>> msg[' subject '] = subject>>> msg[' from '] =  sender>>> msg[' to '] = receivers>>> msg[' CC '] = copyto>> > print msgFrom nobody Tue Aug 11 10:54:59 2015Content-Type:  text/plain; charset= "Us-ascii" mime-version: 1.0content-transfer-encoding: 7bitsubject:  Test mailfrom: [email protected]to: [email protected]cc: [email protected] 123456

Just like this, is a plain text format, by the way, the Mimetext function can also specify the second parameter as the format, for example, HTML format, which can be referred to here:

Https://docs.python.org/2/library/email.mime.html#email.mime.text.MIMEText

2, the recipient can receive, CC people and the dark send people are not receiving?

This really tangled up a lot of time, and the key is that the recipient received the mail below is a copy of the person!

This makes me suspect that the Smtplib module does not support CC!

Later I found a vague answer that you want to add cc and Bcc to list! I feel sure can solve, and then I continue to check down, sure enough you only need the following line of code to do!

Receivers = receivers + CopyTo

The second parameter of the. SendMail method, which is the recipient parameter, specifies all the people who can receive the message, so we're going to merge the recipients, Cc's, and dark send together.

The specific person who is the recipient and CC has already been formatted in the Mimetext function and will be assigned to. SendMail's third parameter

You can refer to this:

Https://docs.python.org/2/library/smtplib.html#smtplib.SMTP.sendmail

3, Python standard input readline and readlines difference

#!/usr/bin/env python#-*-coding:utf-8-*-# name:1.pyimport syswhile true:line = Sys.stdin.readline () if not Lin E:break Sys.stdout.write (line)--------------------------------------------------------------------------------- ---[[email protected] tmp]# printf "1\n2\n3" |./1.py 123
#!/usr/bin/env python#-*-coding:utf-8-*-# name:2.pyimport sysfor i in Sys.stdin.readlines (): Sys.stdout.write (i)-- -----------------------------------------------------------------------------------[[Email protected] tmp]# printf "1\n2\n3\n" |./2.py 123

difference between the. ReadLine () method and the. ReadLines () method (two methods are not part of the Sys.stdin method)

Therefore, the Python standard input and output issue is not discussed.

⑴, ReadLine is read in line until the end of the line break is encountered.

#!/usr/bin/env python#-*-coding:utf-8-*-# name:1.pyimport sysprint sys.stdin.readline ()--------------------------- ---------------------------------------------------------[[email protected] tmp]# printf "1" |./1.py 1[[email Protected] tmp]# printf "1\n" |./1.py 1[[email protected] tmp]# printf "1\n2" |./1.py 1[[email protected] tmp]# printf " 1\n\n "|./1.py 1

⑵, ReadLines reads everything, saves them as a list

#!/usr/bin/env python#-*-coding:utf-8-*-# name:2.pyimport sysprint sys.stdin.readlines ()-------------------------- ----------------------------------------------------------[[email protected] tmp]# printf "1\n2" |./2.py [' 1\n ', ' 2 '] [[email protected] tmp]# printf "1\n2\n" |./2.py [' 1\n ', ' 2\n ']

4. The Getopt function returns two tables, and the two tables are saved separately.

#-*-Coding:utf-8-*-# name:test.pyimport sys,getoptopts, args = Getopt.getopt (sys.argv[1:], ' s:r: ', [' Help ', ' text= ']) Print Optsprint args------------------------------------------------------------------------------------[[email Protected] tmp]#./test.py-s sss-r RRR--help--text abc[('-s ', ' SSS '), ('-R ', ' RRR '), ('--help ', '), ('--text ', ' abc ') ][][[email protected] tmp]#./test.py-s sss-r RRR--help--text ABC other-h[('-s ', ' SSS '), ('-R ', ' RRR '), ('--help ', ' ), ('--text ', ' abc ') [' Other ', '-h '] #这样看来第二个表格用来寸未定义的参数

parameter how to write reference here:

Https://docs.python.org/2/library/getopt.html#getopt.getopt


Python script sends alert message

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.