利用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实现连接mongodb的方法
May 08 Python
举例讲解Python中的Null模式与桥接模式编程
Feb 02 Python
Python实现 多进程导入CSV数据到 MySQL
Feb 26 Python
对python抓取需要登录网站数据的方法详解
May 21 Python
TensorFlow实现简单卷积神经网络
May 24 Python
详解python 注释、变量、类型
Aug 10 Python
python实现图片识别汽车功能
Nov 30 Python
python 采用paramiko 远程执行命令及报错解决
Oct 21 Python
python中的RSA加密与解密实例解析
Nov 18 Python
python3.8.1+selenium实现登录滑块验证功能
May 22 Python
python简单实现9宫格图片实例
Sep 03 Python
Python + opencv对拍照得到的图片进行背景去除的实现方法
Nov 18 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系列学习之日期函数使用介绍
2012/08/18 PHP
PHP获取用户的浏览器与操作系统信息的代码
2012/09/04 PHP
php使用curl发送json格式数据实例
2013/12/17 PHP
php匹配字符中链接地址的方法
2014/12/22 PHP
PHP 配置后台登录以及模板引入
2017/01/24 PHP
php实现微信公众号创建自定义菜单功能的实例代码
2019/06/11 PHP
jquery 简单导航实现代码
2009/09/11 Javascript
常用的JavaScript验证正则表达式汇总
2013/11/26 Javascript
遍历DOM对象内的元素属性示例代码
2014/02/08 Javascript
JavaScript 实现完美兼容多浏览器的复制功能代码
2015/04/28 Javascript
完善的jquery处理机制
2016/02/21 Javascript
详解微信小程序 相对定位和绝对定位
2017/05/11 Javascript
详解使用Typescript开发node.js项目(简单的环境配置)
2017/10/09 Javascript
VUE2实现事件驱动弹窗示例
2017/10/21 Javascript
JS Input里添加小图标的两种方法
2017/11/11 Javascript
JS/jQuery实现获取时间的方法及常用类完整示例
2019/03/07 jQuery
js实现图片无缝循环轮播
2019/10/28 Javascript
Vue中import from的来源及省略后缀与加载文件夹问题
2020/02/09 Javascript
解决Vue-cli3没有vue.config.js文件夹及配置vue项目域名的问题
2020/12/04 Vue.js
[58:25]VP vs RNG 2019国际邀请赛小组赛 BO2 第一场 8.15
2019/08/17 DOTA
Python基于TCP实现会聊天的小机器人功能示例
2018/04/09 Python
python  创建一个保留重复值的列表的补码
2018/10/15 Python
Python函数的定义方式与函数参数问题实例分析
2019/12/26 Python
python GUI库图形界面开发之PyQt5拖放控件实例详解
2020/02/25 Python
python获取栅格点和面值的实现
2020/03/10 Python
python读取配置文件方式(ini、yaml、xml)
2020/04/09 Python
Python爬取YY评级分数并保存数据实现过程解析
2020/06/01 Python
Python获取指定网段正在使用的IP
2020/12/14 Python
突袭HTML5之Javascript API扩展2—地理信息服务及地理位置API学习
2013/01/31 HTML / CSS
工商企业管理应届生求职信
2014/05/04 职场文书
机械设计专业大学生职业生涯规划书范文
2014/09/13 职场文书
小学教师师德师风自我剖析材料
2014/09/29 职场文书
高校自主招生校长推荐信
2015/03/23 职场文书
观看《杨善洲》宣传教育片心得体会
2016/01/23 职场文书
利用Python网络爬虫爬取各大音乐评论的代码
2021/04/13 Python
在Centos 8.0中安装Redis服务器的教程详解
2022/03/21 Redis