脚本过于简单,供学习和参考。主要了解一下smtplib库的使用和超时机制的实现。使用signal.alarm实现超时机制。

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import time

import sys

import logging

import smtplib

import socket

import signal

import ConfigParser

from datetime import datetime

from email import encoders

from email.header import Header

from email.mime.text import MIMEText

from email.utils import parseaddr,formataddr

CONF_PATH = "/etc/zabbix/alarm_email.conf"

logging.basicConfig(level=logging.INFO,format='%(asctime)s [%(levelname)s]: %(message)s',filename='/var/log/zabbix/send_alarm_email.log')

class EmailObject:

def __init__(self,to_addr,content):

self.timeout = 10

self.retry = 3

self.cp = self._parse_config()

self.cpl = self._parse_config().sections()

self.conf = dict(self.cp.items(self.cpl[0]))

# common how to use one

self.to_addr = to_addr

self.content = content

# get ConfigParser,for section selection

def _parse_config(self):

cp = ConfigParser.ConfigParser()

cp.read(CONF_PATH)

return cp

# set base config

def _conf_parse(self):

self.subject = "zabbix告警"

self.from_addr = self.conf["from_addr"]

self.password = self.conf["password"]

self.smtp_server = self.conf["smtp_server"]

def _msg_parse(self):

#msg = self.content.split("*")

#state = "alarm" if msg[0] == "PROBLEM" else "ok"

#severity = msg[1]

#head_time = map(int,msg[2].split("."))

#tail_time = map(int,msg[3].split(":"))

## if not host?

#event_type = "host." + msg[4]

#reason = msg[5].replace("_"," ")

#alarm_id = int(msg[6])

#message = msg

return self.content

def _change_server(self):

# if len = 1 and this fun is called,means that all servers hava been tried

if(len(self.cpl) > 1):

self.cpl.pop(0)

self.retry = 3

self.conf = dict(self.cp.items(self.cpl[0]))

logging.info("Change server to {}".format(self.cpl[0]))

self.send_email()

else:

logging.warning("No server could be used,try to config more server(now is {}) or increase the timeout [{}]!".format(self.cp.sections(),self.timeout))

exit()

def send_email(self):

# signal handle

def handler(signum,frame):

if self.retry > 0:

raise AssertionError

else:

self._change_server()

self._conf_parse()

from_addr = self.from_addr

password = self.password

smtp_server = self.smtp_server

timeout = self.timeout

to_addr = self.to_addr

msg = MIMEText(self.content,'plain','utf-8')

msg['Subject'] = Header(self.subject,'utf-8')

msg['From'] = 'AlarmEmail'+''

msg['To'] = "******@******.com"

try:

signal.signal(signal.SIGALRM,handler)

signal.alarm(timeout)

server = smtplib.SMTP_SSL(smtp_server,465)

server.login(from_addr,password)

server.sendmail(from_addr,msg.as_string())

logging.info("Send email successfully!From:[{}],To:[{}],Content:[{}]".format(from_addr,self.content))

server.quit()

exit()

except AssertionError:

self.retry -= 1

logging.info("Begin to resend email for the {}th times".format(3-self.retry))

self.send_email()

except smtplib.SMTPAuthenticationError,e:

logging.error("Server [{}] authentication failed".format(smtp_server))

self._change_server()

'''

example:

from emailtest import emailtest

eb = emailtest.EmailObject("******@******.com","test content")

eb.send_email()

tips:

increase timeout:

eb.timeout = 10

increase retry times:

eb.retry = 5

'''

配置文件参考如下:

[default]

from_addr = ******@******.com

password = ******

smtp_server = smtp.******.com

[163]

from_addr = ******@163.com

password = ******

smtp_server = smtp.163.com

[qq]

from_addr = ******@qq.com

password = ******

smtp_server = smtp.qq.com

以上这篇利用python实现简单的邮件发送客户端示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程小技巧。

python实现邮件客户端_利用python实现简单的邮件发送客户端示例相关推荐

  1. python post请求 上传图片_利用python模拟实现POST请求提交图片的方法

    本文主要给大家介绍的是关于利用python模拟实现POST请求提交图片的方法,分享出来供大家参考学习,下面来一看看详细的介绍: 使用requests来模拟HTTP请求本来是一件非常轻松的事情,比如上传 ...

  2. python制作图片墙_利用python生成照片墙的示例代码

    PIL(Python Image Library)是python的第三方图像处理库,但是由于其强大的功能与众多的使用人数,几乎已经被认为是python官方图像处理库了.其官方主页为:PIL. PIL历 ...

  3. python读取sas数据集_利用Python获取SAS和R自带数据集

    图:北京-奥森公园-2018年4月 无论是SAS.R还是Python,本身都自带一些数据集,对于初学者来说,可以通过这些自带的小数据集进行编程练习,无疑是非常方便的.SAS.R作为统计分析软件,本身自 ...

  4. python英语词汇读音_利用Python制作查单词小程序(一):抓取来自百度翻译的单词释义和音标...

    小编在学习英语的时候,遇到不认识的英语单词,会用百度翻译来查询单词的释义和音标,并播放单词的读音.为了便于复习和记忆,需要将单词的释义和音标以复制粘贴的方式保存到本地. 这个过程非常繁琐,于是小编就想 ...

  5. python监控短信_利用Python实现手机短信监控通知的方法

    日常运维工作中,通常是邮件报警机制,但邮件可能不被及时查看,导致问题出现得不到及时有效处理.所以想到用Python实现发短信功能,当监控到问题出现时,短信报警,使问题能得到及时的处理.当然,我相信,用 ...

  6. python处理nc数据_利用python如何处理nc数据详解

    利用python如何处理nc数据详解 来源:中文源码网    浏览: 次    日期:2018年9月2日 [下载文档:  利用python如何处理nc数据详解.txt ] (友情提示:右键点上行txt ...

  7. python怎么算积分_利用python求积分的实例

    利用python求积分的实例 python的numpy库集成了很多的函数.利用其中的函数可以很方便的解决一些数学问题.本篇介绍如何使用python的numpy来求解积分. 代码如下: # -*- co ...

  8. python制作电脑软件_利用PYTHON制作桌面版爬虫软件(一)

    抱歉,对长沙房地产数据的挖掘与分析[三],想了蛮久,觉得对自己的分析结果不是很理想.等我完善好了,我再发出来吧.今天继续开启新的一专题.主要讲解如何用PYTHON实现简单的桌面软件的制作. 题外话,我 ...

  9. python计算面积代码_利用Python求阴影部分的面积实例代码

    利用Python求阴影部分的面积实例代码 来源:中文源码网    浏览: 次    日期:2019年11月5日 [下载文档:  利用Python求阴影部分的面积实例代码.txt ] (友情提示:右键点 ...

最新文章

  1. ascii码对照表十六进制_ASCII
  2. 机器视觉:Caffe Python接口多进程提取特征
  3. python3列表del 语句
  4. 交叉驰豫的影响因素_深度讲解:膝关节韧带为什么容易断裂?这5点因素影响非常大...
  5. lucene域的各种类型
  6. 重庆航天职业技术学院计算机系在哪个校区,2020年重庆航天职业技术学院地址在哪里...
  7. Stellarium Windows/Linux编译记录
  8. 世界通用闹铃(闹钟铃声)铃声 世界通用闹铃(闹钟铃声)手机铃声...
  9. linux i2c模型 rtc模型 详细分析,Linux RTC驱动分析(一)----pcf8563驱动和class.c
  10. 【云原生学习】史上最全Prometheus学习笔记
  11. [Ora]-1309. OCI is not properly installed on this machine (NOE1/INIT)或者[FireDAC][Phys][Ora]-314. Can
  12. 南通大学计算机学院顾飘,解密通大软件专业“学霸”们的考研之路_南通大学...
  13. BBR学习笔记--什么是BBR、可调整的参数
  14. airodump-ng界面参数比较详细的解释
  15. 「雅礼集训」市场--势能线段树
  16. SoundTouch变调编译以及算法代码详解
  17. Mac os 向NS Switch拷贝文件 switch/sxos 无法识别的解决办法
  18. 【转】基于TMS320C6455的千兆以太网设计
  19. 聊聊GIS中那些坐标系
  20. no such file or directory @ realpath_rec xxx.xib

热门文章

  1. LeetCode 103. 二叉树的锯齿形层次遍历(BFS / 双栈)
  2. 强基计划对计算机,你对报考强基计划怎么看?
  3. 华为服务器上传文件后怎么通过链接查看,远程服务器文件上传后的操作
  4. 1.数据库基本概念知识
  5. linux中UDP程序流程、客户端、服务端
  6. python中的面向对象:类与对象(重点!!!)
  7. java基础之lambda表达式
  8. Hive关于数据表的增删改(内部表、外部表、分区表、分桶表 数据类型、分隔符类型)
  9. YUI事件体系之Y.Do
  10. 图谱实战 | 基于半结构化百科的电影KG构建、查询与推理实践记录