邮件附件自动处理相关

需求:每天邮箱里收到一封特定的邮件,里面的附件内容需要入库后并回复邮件,附件格式都是txt,内容也相对简单,每行一个数字序列号

写了一个简单能用的办法,用Python定时收取邮件,匹配到指定关键字然后处理

系统版本:CentOS 6.9 x64,Python版本3.6.3

from imbox import Imbox
import shutil
import yagmail
import time
import os
import sys
import fcntl, sys
pid_file = '/tmp/.black_sw.pid'    # 创建文件锁,确保脚本不会重复运行
fp = open(pid_file, 'w')
try:
    fcntl.lockf(fp, fcntl.LOCK_EX  |  fcntl.LOCK_NB)
except IOError:
          #  print ('another instance is running')
        sys.exit(0)
a = os.path.exists("/tmp/.black_sw.txt")
if  a :
    sys.exit()
imap_cc = 'imap.exmail.qq.com'
username = 'sa_sys@qq.com'
password = '123456'
file_dir = '/data/etl/mail_report/'
block_list = ['zhangsan@qq.com', 'lisi@qq.com']
yag = yagmail.SMTP(user=username, password=password, host=imap_cc)
day = time.strftime("%Y%m%d")
with Imbox(imap_cc,
            username=username,
            password=password,
            ssl=True,
            ssl_context=None,
            starttls=False) as imbox:
                unread_messages = imbox.messages(unread=True)
            for  uid, b  in  unread_messages:
                    if  '每日序列号'  in  b.subject  or  '序列号入库操作'  in  b.subject:     # 搜索指定邮件标题
                        try:
                                to_list = []
                            for  i  in  b.sent_to:
                                    to_list.append(i['email'])
                            to_list.append(b.sent_from[0]['email'])
                            to_list.remove(username)
                            to_list = [x for  x  in  to_list  if  (x  not   in  block_list)]
                            print (to_list)                    
                            cc_list = []
                            for  i  in  b.cc:
                                    cc_list.append(i['email'])
                            cc_list = [x for  x  in  cc_list  if  (x  not   in  block_list)]
                            print (cc_list)
                        except:
                            yag.send(to=username, subject = '{}处理收件人异常'.format(b.subject))
                            sys.exit()

                        try:
                                file = b.attachments[0]['content']

                            with open(file_dir+'{}.txt'.format(day),  'wb') as f:
                                        shutil.copyfileobj(file, f)
                                f = open(file_dir + '{}.txt'.format(day))
                                a = f.readlines()[0:5]
                                if  a[1].startswith('1'):
                                        var = os.system('/data/etl/mail_report/etl.sh')   # 调用号码入库的脚本
                                        print ("var", var)
                                        if  var  ==  0:
                                                try:
                                                        yag = yagmail.SMTP(user=username, password=password,
                                                                           host=imap_cc)
                                                yag.send(
                    to=to_list, subject = b.subject, contents = '已处理。', cc = cc_list)
                                                os.system('echo "1" >/tmp/.black_sw.txt')
                                                imbox.mark_seen(uid)
                                            except Exception as e:
                                                yag.send(to=username, subject = '每日入库邮件处理异常_status=98'.format(
                    day), contents = e)
                                         else:
                                            yag.send(to=username, subject = '每日入库邮件处理异常_status=99'.format(day))
                                     else:
                                        yag.send(to=username, subject = '每日入库邮件处理异常_status=100'.format(day))

                         except:
                                    yag.send(to=username, subject = '{}附件异常'.format(b.subject))
搜索