利用python实现简单的邮件发送客户端示例


Posted in Python onDecember 23, 2017

脚本过于简单,供学习和参考。主要了解一下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'+'<'+from_addr+'>'  
    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,to_addr, msg.as_string())
      logging.info("Send email successfully!From:[{}],To:[{}],Content:[{}]".format(from_addr,to_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中的ctime()方法使用教程
May 22 Python
Python selenium文件上传方法汇总
Nov 19 Python
CentOS 7下Python 2.7升级至Python3.6.1的实战教程
Jul 06 Python
Windows下的Jupyter Notebook 安装与自定义启动(图文详解)
Feb 21 Python
对pandas中to_dict的用法详解
Jun 05 Python
Python3多进程 multiprocessing 模块实例详解
Jun 11 Python
浅谈python 导入模块和解决文件句柄找不到问题
Dec 15 Python
详解Python函数式编程—高阶函数
Mar 29 Python
Python+OpenCV+pyQt5录制双目摄像头视频的实例
Jun 28 Python
django和flask哪个值得研究学习
Jul 31 Python
python中requests模拟登录的三种方式(携带cookie/session进行请求网站)
Nov 17 Python
Python各协议下socket黏包问题原理
Apr 12 Python
python初学之用户登录的实现过程(实例讲解)
Dec 23 #Python
python的numpy模块安装不成功简单解决方法总结
Dec 23 #Python
windows 下python+numpy安装实用教程
Dec 23 #Python
Python实现字典的遍历与排序功能示例
Dec 23 #Python
Python实现字典按照value进行排序的方法分析
Dec 23 #Python
Python使用Matplotlib实现雨点图动画效果的方法
Dec 23 #Python
简单了解什么是神经网络
Dec 23 #Python
You might like
PHP Class&amp;Object -- 解析PHP实现二叉树
2013/06/25 PHP
PC端微信扫码支付成功之后自动跳转php版代码
2017/07/07 PHP
PHP合并两个或多个数组的方法
2019/01/20 PHP
javascript 实现简单的table排序及table操作练习
2012/12/28 Javascript
js switch case default 的用法示例介绍
2013/10/23 Javascript
JQUERY 设置SELECT选中项代码
2014/02/07 Javascript
jQuery实现冻结表头的方法
2015/03/09 Javascript
jQuery在ul中显示某个li索引号的方法
2015/03/17 Javascript
JQuery选中checkbox方法代码实例(全选、反选、全不选)
2015/04/27 Javascript
jQuery满屏焦点图左右滚动特效代码分享
2015/09/07 Javascript
基于d3.js实现实时刷新的折线图
2016/08/03 Javascript
使用BootStrap实现表格隔行变色及hover变色并在需要时出现滚动条
2017/01/04 Javascript
Vue组件选项props实例详解
2017/08/18 Javascript
总结JavaScript在IE9之前版本中内存泄露问题
2018/04/28 Javascript
一文秒懂nodejs中的异步编程
2021/01/28 NodeJs
Python在Windows和在Linux下调用动态链接库的教程
2015/08/18 Python
使用python实现生成用户信息
2017/03/20 Python
Python cookbook(数据结构与算法)通过公共键对字典列表排序算法示例
2018/03/15 Python
Python3解释器知识点总结
2019/02/19 Python
django的聚合函数和aggregate、annotate方法使用详解
2019/07/23 Python
Python 读取有公式cell的结果内容实例方法
2020/02/17 Python
Python对称的二叉树多种思路实现方法
2020/02/28 Python
Python Selenium 设置元素等待的三种方式
2020/03/18 Python
python+selenium+chromedriver实现爬虫示例代码
2020/04/10 Python
python中关于数据类型的学习笔记
2020/07/19 Python
CSS3中:nth-child和:nth-of-type的区别深入理解
2014/03/10 HTML / CSS
C#如何调用Word并打开一个Word文档
2013/05/08 面试题
大学生年度自我鉴定
2013/10/31 职场文书
岗位职责的含义
2013/11/17 职场文书
中文师范生自荐信
2014/01/30 职场文书
大学生军训自我鉴定
2014/02/12 职场文书
学校出纳员岗位职责
2014/03/18 职场文书
工地宣传标语
2014/06/18 职场文书
2014年作风建设心得体会
2014/10/22 职场文书
天鹅湖观后感
2015/06/09 职场文书
php远程请求CURL案例(爬虫、保存登录状态)
2021/04/01 PHP