Python通过smtp服务发送电子邮件给指定用户(适用于Zabbix邮件报警)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python通过smtp服务发送电子邮件给指定用户(适用于Zabbix邮件报警)相关的知识,希望对你有一定的参考价值。
当下免费的邮件服务很多,例如163企业邮箱、QQ企业邮箱等。不需要自己搭建邮件服务器发送邮件给指 定用户,只需要注册任何一个支持smtp协议的邮箱就可以实现发送邮件。发送邮件可以通过Linux命令、自己编写的Shell脚本,也可以通过Python写的Python脚本。
如下代码是一个简单却实用的示例。默认无参数执行时,发送预设的邮件主题和邮件内容到预设的用户。带参数执行时将指定的主题和邮件内容发送到指定的用户。带参数执行可用于Zabbix邮件报警脚本。
对于Zabbix2.x可以直接填写脚本名字。对于Zabbix3.x,需要指定参数,第一个是参数1,第二个是参数2,以此类推。
如下图所示:
代码如下:
#!/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 = ‘[email protected]‘ # change it EMAIL_HOST_PASSWORD = ‘your password‘ # change it DEFAULT_FROM_EMAIL = ‘[email protected]‘ # change it CRLF = "\r\n" # for Windows user read easily EMAIL_TO = "[email protected]" # 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--
本文出自 “通信,我的最爱” 博客,请务必保留此出处http://dgd2010.blog.51cto.com/1539422/1786821
以上是关于Python通过smtp服务发送电子邮件给指定用户(适用于Zabbix邮件报警)的主要内容,如果未能解决你的问题,请参考以下文章