#!/usr/bin/python3
#!-*- coding: utf-8-*-
import smtplib
import time
import sys
import os
import logging
import logging.handlers
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
#time_out
CONN_TIME_OUT=10
MAIL_LOG_LEVEL=0
ENCODING="UTF-8"
KB=1024
MB=1024*KB
LEVELS = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL}
LOG_FILENAME = 'mail_helper_log.out'
#logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,)
#logger=logging.getLogger('MyLogger')
#handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=5*MB, backupCount=15, encoding=ENCODING)
#logger.addHandler(handler)
class MailHelper:
"""
create an mailUtil instance and pass some vars.
Usage:
mailUtil=mail.MailHelper("mexcn01.nhncorp.cn", "CN90056", "CN90056", smtp_port=25)
mailUtil.setFrom("noreply@nhn.com")
mailUtil.setLogLevel("info")
mailUtil.send("A3mao.zzg@nhn.com", "subject", "body message")
"""
def __init__(self, smtp_host, smtp_user, smtp_password, smtp_port=25,
time_out=CONN_TIME_OUT):
self.smtp_host=smtp_host
self.smtp_port=smtp_port
self.smtp_user=smtp_user
self.smtp_password=smtp_password
self.time_out=time_out
self.mail=MIMEMultipart('related')
self.alter=MIMEMultipart('alternative')
self.mail.attach(self.alter)
self.debug_level=MAIL_LOG_LEVEL
self.logger=logging.getLogger('MyLogger')
logFile=os.path.join(os.getenv("HOME"), LOG_FILENAME)
self.handler = logging.handlers.RotatingFileHandler(logFile,
maxBytes=5*MB, backupCount=15, encoding=ENCODING)
self.logger.addHandler(self.handler)
def setLogLevel(self, level_name):
"""
set debug level, when 1 on else off
"""
level = LEVELS.get(level_name, logging.NOTSET)
self.logger.setLevel(level)
#logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,)
# only debug can display the log message
if(int(level)== 10):
self.debug_level=1
else:
self.debug_level=MAIL_LOG_LEVEL
def setFrom(self, mail_from):
"""
set mail from
"""
self._from=mail_from
self.mail["From"]=mail_from
def send(self, toAddr, subject, msg_body, msg_body_type='html', encoding=ENCODING):
"""
send email
"""
currentTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
self.logger.info("send messgae \n[\n\t Subject : {0:>5} \n\t From : {1} \n\t To : {2} \n\t Time : {3}\n\t Message : {4:>5} \n] ".format(subject, self.mail["From"], toAddr, currentTime, msg_body))
if (type(toAddr) == list):
self.mail['To'] = ','.join(toAddr)
elif (type(toAddr) == str):
self.mail['To'] = toAddr
else:
raise Exception('invalid mail to')
if(msg_body_type == 'html'):
self.alter.attach(MIMEText(msg_body, 'html', encoding))
else:
self.alter.attach(MIMEText(msg_body, 'plain', encoding))
self.mail['Subject'] = subject
self.mail['Date'] = currentTime
server = False
try:
server = smtplib.SMTP(self.smtp_host, self.smtp_port, self.time_out)
server.set_debuglevel(self.debug_level)
server.login(self.smtp_user, self.smtp_password)
server.sendmail(self.mail["From"], self.mail['To'], self.mail.as_string())
return True
except Exception as e:
logging.error(sys.exc_info())
return False
finally:
server and server.quit()
self.logger.info("********************* send mail finished and quit ********************* ")
调用
上面为文件 mail_helper.py
mailhelper=mail.MailHelper(smtp_host, smtp_user, smtp_password, smtp_port=25)
mailhelper.setFrom(smtp_from)
mailhelper.setLogLevel("info")
currentTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
mailhelper.send(smtp_to, "Warning!! monitor mail : " + currentTime, content)
分享到:
相关推荐
基于Python实现多进程的发送邮件.zip
使用python3自带的库实现邮件发送,包括主题、附件等,可直接使用
Python发邮件代码
python3 多账户发邮件代码:是使用python3 进行开发的,可以同时对多个账号邮箱进行发送邮件,可以直接运行
python GUI实现简易发送邮件程序。
使用python代码自动发送邮件,运行前请先将邮箱地址及密码改成自己的
python发送邮件代码,服务器配置请自行修改,脚本中的地址是内网搭建的邮件服务器。可以结合系统定时任务配置邮件定时发送。希望帮到你
Python自动发送邮件并添加附件的源代码,真特定网站,比较具有参考价值
python3自动发邮件脚本,以QQ邮箱为例,自己配置发送邮箱和授权码
基于Python的电子邮件自动发送程序设计.pdf
python发邮件程序,发送方法:./mail.py 收件人 主题 html内容 图片文件 附件文件'
简单的python发送邮件的示例,基于python2.7
2 利用Python发送邮件 2.1 发送一封简单的电子邮件 2.2 发送含HTML样式的电子邮件 2.3 发送带附件的电子邮件 2.4 以邮件的内容发送,而不是作为附件形式发送 2.5 群发邮件 2.6 定时发送邮件 2.7 发送CSV文件...
python发送邮件报表
python email模块发送office附件. 本文编写了python 邮件发附件方法。代码解释。
为了方便大量发送邮件,使用python语言smtplib函数编写了简单的脚本。只需要填写正确的qq邮箱账号 ,即可发送。
该文档介绍了两种利用python发送邮件的方式,包括响应模块导入,邮件正文等。
python 代码 发送邮件,使用QQ邮箱,要用其他邮箱 根据需要自行修改。使用前先调试成功,密码不是网页登陆邮箱的密码,是QQ邮箱分配的一个什么码。需从网页登陆邮箱后,开启一个功能,邮箱分配的一个密码。
python爬虫发邮件示例demo,亲自在本地跑过的,都能正常运行,有问题可以私聊我,算是python入门学习吧