利用python实现简单的邮件发送客户端示例
作者:jingxian 时间:2022-06-19 18:25:07
脚本过于简单,供学习和参考。主要了解一下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
来源:http://blog.csdn.net/u012013290/article/details/78867506
标签:python,邮件发送,客户端
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
javascript for-in有序遍历json数据并探讨各个浏览器差异
2024-05-25 15:18:17
![](https://img.aspxhome.com/file/2023/7/123717_0s.png)
Golang中time.After的使用理解与释放问题
2024-04-25 13:20:08
![](https://img.aspxhome.com/file/2023/1/134291_0s.png)
Javascript 回调和事件(翻译)
2009-03-28 11:47:00
Python3 replace()函数使用方法
2023-07-21 22:25:13
Python 使用input同时输入多个数的操作
2023-09-23 22:36:42
![](https://img.aspxhome.com/file/2023/8/107138_0s.jpg)
python复制列表时[:]和[::]之间有什么区别
2021-08-15 01:22:05
如何使用python生成大量数据写入es数据库并查询操作
2024-01-22 18:00:55
![](https://img.aspxhome.com/file/2023/0/104990_0s.png)
一个Access数据库数据传递的实例方法
2008-11-28 16:24:00
flask 实现上传图片并缩放作为头像的例子
2021-09-08 06:32:42
Python详解如何动态给对象增加属性和方法
2022-11-14 23:00:46
![](https://img.aspxhome.com/file/2023/4/102744_0s.png)
python实现桌面气泡提示功能
2023-07-13 06:37:13
![](https://img.aspxhome.com/file/2023/0/94070_0s.jpg)
UTF-8 编码中BOM的检测与删除
2022-06-04 07:44:16
PyQt4编程之让状态栏显示信息的方法
2021-07-22 04:11:19
django将图片上传数据库后在前端显式的方法
2024-01-12 21:17:34
Mysql数据库清理binlog日志命令详解
2024-01-14 09:04:07
![](https://img.aspxhome.com/file/2023/4/96494_0s.jpg)
Python二叉搜索树与双向链表转换算法示例
2023-07-17 22:49:42
mysql启动时出现ERROR 2003 (HY000)问题的解决方法
2024-01-22 02:53:13
![](https://img.aspxhome.com/file/2023/7/110327_0s.png)
python中Tkinter复选框Checkbutton是否被选中判断
2023-10-20 16:41:19
![](https://img.aspxhome.com/file/2023/0/118790_0s.png)
Perl字符串处理函数大全
2023-11-25 17:33:35
Python3.X 线程中信号量的使用方法示例
2022-06-12 12:07:13
![](https://img.aspxhome.com/file/2023/3/107243_0s.png)