python实现邮件客户端_利用python实现简单的邮件发送客户端示例
脚本过于简单,供学习和参考。主要了解一下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实现简单的邮件发送客户端示例相关推荐
- python post请求 上传图片_利用python模拟实现POST请求提交图片的方法
本文主要给大家介绍的是关于利用python模拟实现POST请求提交图片的方法,分享出来供大家参考学习,下面来一看看详细的介绍: 使用requests来模拟HTTP请求本来是一件非常轻松的事情,比如上传 ...
- python制作图片墙_利用python生成照片墙的示例代码
PIL(Python Image Library)是python的第三方图像处理库,但是由于其强大的功能与众多的使用人数,几乎已经被认为是python官方图像处理库了.其官方主页为:PIL. PIL历 ...
- python读取sas数据集_利用Python获取SAS和R自带数据集
图:北京-奥森公园-2018年4月 无论是SAS.R还是Python,本身都自带一些数据集,对于初学者来说,可以通过这些自带的小数据集进行编程练习,无疑是非常方便的.SAS.R作为统计分析软件,本身自 ...
- python英语词汇读音_利用Python制作查单词小程序(一):抓取来自百度翻译的单词释义和音标...
小编在学习英语的时候,遇到不认识的英语单词,会用百度翻译来查询单词的释义和音标,并播放单词的读音.为了便于复习和记忆,需要将单词的释义和音标以复制粘贴的方式保存到本地. 这个过程非常繁琐,于是小编就想 ...
- python监控短信_利用Python实现手机短信监控通知的方法
日常运维工作中,通常是邮件报警机制,但邮件可能不被及时查看,导致问题出现得不到及时有效处理.所以想到用Python实现发短信功能,当监控到问题出现时,短信报警,使问题能得到及时的处理.当然,我相信,用 ...
- python处理nc数据_利用python如何处理nc数据详解
利用python如何处理nc数据详解 来源:中文源码网 浏览: 次 日期:2018年9月2日 [下载文档: 利用python如何处理nc数据详解.txt ] (友情提示:右键点上行txt ...
- python怎么算积分_利用python求积分的实例
利用python求积分的实例 python的numpy库集成了很多的函数.利用其中的函数可以很方便的解决一些数学问题.本篇介绍如何使用python的numpy来求解积分. 代码如下: # -*- co ...
- python制作电脑软件_利用PYTHON制作桌面版爬虫软件(一)
抱歉,对长沙房地产数据的挖掘与分析[三],想了蛮久,觉得对自己的分析结果不是很理想.等我完善好了,我再发出来吧.今天继续开启新的一专题.主要讲解如何用PYTHON实现简单的桌面软件的制作. 题外话,我 ...
- python计算面积代码_利用Python求阴影部分的面积实例代码
利用Python求阴影部分的面积实例代码 来源:中文源码网 浏览: 次 日期:2019年11月5日 [下载文档: 利用Python求阴影部分的面积实例代码.txt ] (友情提示:右键点 ...
最新文章
- ascii码对照表十六进制_ASCII
- 机器视觉:Caffe Python接口多进程提取特征
- python3列表del 语句
- 交叉驰豫的影响因素_深度讲解:膝关节韧带为什么容易断裂?这5点因素影响非常大...
- lucene域的各种类型
- 重庆航天职业技术学院计算机系在哪个校区,2020年重庆航天职业技术学院地址在哪里...
- Stellarium Windows/Linux编译记录
- 世界通用闹铃(闹钟铃声)铃声 世界通用闹铃(闹钟铃声)手机铃声...
- linux i2c模型 rtc模型 详细分析,Linux RTC驱动分析(一)----pcf8563驱动和class.c
- 【云原生学习】史上最全Prometheus学习笔记
- [Ora]-1309. OCI is not properly installed on this machine (NOE1/INIT)或者[FireDAC][Phys][Ora]-314. Can
- 南通大学计算机学院顾飘,解密通大软件专业“学霸”们的考研之路_南通大学...
- BBR学习笔记--什么是BBR、可调整的参数
- airodump-ng界面参数比较详细的解释
- 「雅礼集训」市场--势能线段树
- SoundTouch变调编译以及算法代码详解
- Mac os 向NS Switch拷贝文件 switch/sxos 无法识别的解决办法
- 【转】基于TMS320C6455的千兆以太网设计
- 聊聊GIS中那些坐标系
- no such file or directory @ realpath_rec xxx.xib