当下免费的邮件服务很多,例如163企业邮箱、QQ企业邮箱等。不需要自己搭建邮件服务器发送邮件给指 定用户,只需要注册任何一个支持smtp协议的邮箱就可以实现发送邮件。发送邮件可以通过Linux命令、自己编写的Shell脚本,也可以通过Python写的Python脚本。
如下代码是一个简单却实用的示例。默认无参数执行时,发送预设的邮件主题和邮件内容到预设的用户。带参数执行时将指定的主题和邮件内容发送到指定的用户。带参数执行可用于Zabbix邮件报警脚本。
对于Zabbix2.x可以直接填写脚本名字。对于Zabbix3.x,需要指定参数,第一个是参数1,第二个是参数2,以此类推。
如下图所示:
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
import
smtplib
import
string
import
sys
def
usage():
print
(
"""
Function: send email to somebody using smtp protocol
Usage:
no parameters: python %s
with parameters: python %s <mailto> <subject> <message body>
Example: python %s "sendto" "subject" "message"
"""
)
%
(__file__, __file__, sys.argv[
0
])
sys.exit(
0
)
EMAIL_HOST
=
"smtp.example.domain"
# change it
EMAIL_PORT
=
25
# default smtp port
EMAIL_HOST_USER
=
'noreply@example.domain'
# change it
EMAIL_HOST_PASSWORD
=
'your password'
# change it
DEFAULT_FROM_EMAIL
=
'noreply@example.domain'
# change it
CRLF
=
"\r\n"
# for Windows user read easily
EMAIL_TO
=
"example@example.domain"
# user defined variable, in Zabbix is {ALERT.SENDTO}
SUBJECT
=
"An email notification from Python"
# user defined variable, in Zabbix is {ALERT.SUBJECT}
text
=
"if you saw this content, it means it works and this is default content with no parameters."
# user defined variable, in Zabbix is {ALERT.MESSAGE}
argc
=
len
(sys.argv)
if
not
(argc
=
=
1
or
argc
=
=
4
):
print
(
"Error: incorrect number of arguments or unrecognized option"
)
usage()
if
argc
=
=
1
:
pass
else
:
if
sys.argv[
1
]
is
not
None
and
sys.argv[
2
]
is
not
None
and
sys.argv[
3
]
is
not
None
:
EMAIL_TO
=
sys.argv[
1
]
SUBJECT
=
sys.argv[
2
]
text
=
sys.argv[
3
]
BODY
=
string.join((
"From: %s"
%
DEFAULT_FROM_EMAIL,
"To: %s"
%
EMAIL_TO,
"Subject: %s"
%
SUBJECT,
"",
text
), CRLF)
server
=
smtplib.SMTP()
server.connect(EMAIL_HOST, EMAIL_PORT)
server.starttls()
server.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD)
server.sendmail(DEFAULT_FROM_EMAIL, [EMAIL_TO], BODY)
server.quit()
|
tag:Python邮件报警,Zabbix邮件报警脚本,Python发送邮件
--end--
本文转自 urey_pp 51CTO博客,原文链接:http://blog.51cto.com/dgd2010/1786821,如需转载请自行联系原作者