读取 root 账号邮件, 并转发

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Last update: 2014-01-03
#Author : aimin
#E-mail : hbfxam@gmail.com
import smtplib
from email import message_from_string
from email.mime.text import MIMEText
class MailParse(smtplib.SMTP):
def __init__(self, srv_info, eml):
smtplib.SMTP.__init__(self)
self.cfg_info = srv_info
self.eml = eml
self.eml_msg = ''
def _parse(self):
"""转换message对象"""
msg = message_from_string(self.eml_msg)
self.eml_msg = ''
parse_data = {'subject' : msg.get("subject"),
'date' : msg.get("date"),
'body': msg.get_payload(decode=True),
'type': msg.get_content_subtype()
}
return parse_data
def _read_eml(self):
"""逐行读取eml文件,以From 开头的行做切割,并处理数据"""
eml_obj = open(self.eml)
for line in eml_obj:
if line.startswith('From ') and self.eml_msg:
parse_data = self._parse()
self._forward(parse_data)
self.eml_msg += line;
else:
if self.eml_msg:
parse_data = self._parse()
self._forward(parse_data)
eml_obj.close()
def _truncate_eml(self):
"""清空eml文件"""
eml_obj = open(self.eml,'w')
eml_obj.truncate()
eml_obj.close()
def process(self):
self._user_auth()
self._read_eml()
self._truncate_eml()
self._login_out()
def _forward(self, parse_data):
"""转发邮件到指定邮箱"""
mail_msg = MIMEText(parse_data['body'] , parse_data['type'], 'utf-8')
mail_msg['Date'] = parse_data['date']
mail_msg['Subject'] = parse_data['subject']
mail_msg['From'] = self.cfg_info['user']
mail_msg['To'] = ';'.join(self.cfg_info['fwd_email'])
# print mail_msg.as_string()
self.sendmail( self.cfg_info['user'], self.cfg_info['fwd_email'] , mail_msg.as_string() )
def _user_auth(self):
"""smtp帐号登录"""
try:
self.connect( self.cfg_info['server'] , self.cfg_info['port'] )
####若邮件服务器未开启tls,则注视下面两行
self.ehlo()
self.starttls()
except:
print 'Connection %s:%s server failure' % (self.cfg_info['server'], self.cfg_info['port'])
else:
try:
self.login( self.cfg_info['user'] , self.cfg_info['passwd'] )
except Exception as err:
print err
def _login_out(self):
self.close()

测试

if __name__ == "__main__":
eml = '/var/spool/mail/root'
login_info = {
'server' : 'mail_server',
'port':25,
'user': 'xxxx',
'passwd':'xxx',
'fwd_email' : ['hbfxam@gmail.com']
}
parse = MailParse(login_info, eml)
parse.process()