首页 > 其他分享 >捕获企业邮箱内容后自动处理邮件,自动回复变化内容

捕获企业邮箱内容后自动处理邮件,自动回复变化内容

时间:2023-01-28 15:46:52浏览次数:41  
标签:server content header 内容 mail print 自动 企业邮箱 email

我需要经常回复领导发给我的邮件,邮件有一些特征。我的想法是通过python获取未读邮件,将符合特征的邮件处理一下。

处理方式是获取到邮件中的客户名称和id,去另外一个页面查询回复内容,查到后在原邮件上回复,原来的发送者是新邮件的接收者,原来的cc和bcc不变,标题加 "回复:",回复后将源邮件改为已读状态

代码:

#-*- encoding: utf-8 -*-
import email,sys,re
from imapclient import IMAPClient
from html.parser import HTMLParser
import requests,smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.message import MIMEMessage

def strip_tags(html, save=None):
    result = []
    start = []
    data = []
 
    def starttag(tag, attrs):
        if tag not in save:
            return
        start.append(tag)
        if attrs:
            j = 0
            for attr in attrs:
                attrs[j] = attr[0] + '="' + attr[1] + '"'
                j += 1
            attrs = ' ' + (' '.join(attrs))
        else:
            attrs = ''
        result.append('<' + tag + attrs + '>')
 
    def endtag(tag):
        if start and tag == start[len(start) - 1]:
            result.append('</' + tag + '>')
 
    parser = HTMLParser()
    parser.handle_data = result.append
    if save:
        parser.handle_starttag = starttag
        parser.handle_endtag = endtag
    parser.feed(html)
    parser.close()
 
    for i in range(0, len(result)):
        tmp = result[i].rstrip('\n')
        tmp = tmp.lstrip('\n')
        if tmp:
            data.append(tmp)
 
    return ''.join(data)

settings = {}
settings['imap_server'] = 'imap.exmail.qq.com';
settings['email'] = '[email protected]';
settings['password'] = 'mimamima';

#服务器网址
hostname = settings['imap_server']
#用户名即邮箱账号
username = settings['email']
#授权码不是邮箱原密码
passwd = settings['password']
#链接服务器
server = IMAPClient(hostname, ssl= True)
#登陆
try:
    #登陆账号
    server.login(username, passwd)
    # 上传客户端身份信息
    server.id_({"name": "IMAPClient", "version": "2.1.0"})
    #导航目录的列表,'INBOX','草稿箱'、'已发送'等
    dictList = server.list_folders()
    # print(dictList)
    #对收件箱只读
    info = server.select_folder('INBOX', readonly = True)
except server.Error:
    print('Could not login')
    sys.exit(1)
    

sender = smtplib.SMTP()
sender.connect(settings['imap_server'])   # 连接 qq 邮箱
sender.login(settings['email'], settings['password'])   # 账号和授权码
                
#获取邮件列表
result = server.search(u'UNSEEN')
for uid in result:
    massageList = server.fetch(uid,['BODY[]'])
    mailBody = massageList[uid][b'BODY[]']
    #邮件内容解析最里面那层是按字节来解析邮件主题内容,这个过程生成Message类型
    try :
        email_content = email.message_from_string(mailBody)
    except TypeError:
        email_content = email.message_from_string(str(email.message_from_bytes(mailBody)))
    
    subject = str(email.header.make_header(email.header.decode_header(email_content['SUBJECT'])))
    mail_from = str(email.header.make_header(email.header.decode_header(email_content['From'])))
    mail_to = str(email.header.make_header(email.header.decode_header(email_content['To'])))
    mail_cc = str(email.header.make_header(email.header.decode_header(email_content['Cc'])))
    mail_received = str(email.header.make_header(email.header.decode_header(email_content['Received'])))
    mail_id = str(email.header.make_header(email.header.decode_header(email_content['Message-ID'])))

    #收件日期
    envlope = (server.fetch(uid,['ENVELOPE']))[uid][b'ENVELOPE']
    dates = envlope.date
    
    # 获取内容的type编码方式
    maintype = email_content.get_content_maintype()
    mail_content1 = b''
    if maintype == 'multipart':
        for part in email_content.get_payload():
            if part.get_content_maintype() == 'text':
                mail_content1 = part.get_payload(decode=True).strip()
            elif part.get_content_maintype() == 'multipart':
                for part2 in part.get_payload():
                    mail_content1 = part2.get_payload(decode=True).strip()
            else:
                pass
    elif maintype == 'text':
        mail_content1 = email_content.get_payload(decode=True).strip()
           
    try:
        #解码显示中文,如果utf-8不行用gbk或者其他
        mail_content = mail_content1.decode('gbk')
    except UnicodeDecodeError:
        try: 
            mail_content = mail_content1.decode('utf-8')
        except UnicodeDecodeError:
            print('decode error')
            sys.exit(1)
    
    mail_content2 = strip_tags(mail_content)
    print('Id: ', mail_id)
    print('From: ', mail_from)
    print('To: ', mail_to)
    print('Cc: ', mail_cc)
    print('Received: ', mail_received)
    print('Subject: ', subject)
    print('Date:',dates)
    print('-'*10, 'mail content', '-'*10)
    print(mail_content)
    print('-'*10, 'mail content', '-'*10)
    print("\n\n")
    
    if re.search('[退款申请]', subject) and not re.search('回复', subject):
        if re.search('小波', mail_content) and re.search('协助查公司退款', mail_content):
            kk = re.compile(r'基础员工已通过(.*?)客户\s*(.*?)\s*(\s*(.*?)ID:(.*?)\s*)(.*?)可以退款(.*?)元')
            tuiinfo = kk.findall(mail_content2)
            kehuname = tuiinfo[0][1]
            kehuid = tuiinfo[0][3]
            kehumoney = tuiinfo[0][5]
            print('kehuname: ', kehuname)
            print('kehuid: ', kehuid)
            print('kehumoney: ', kehumoney)
            print("\n\n")
            
            url = 'https://baidu.com/xxx?&name=%s&id=%s' % (kehuname, kehuid)
            #print("url:%s" % url)
            print("获取回复内容")
            page=requests.get(url)
            html_content = page.text
            html_content2 = strip_tags(html_content)
            if re.search('建议退款', html_content) and not html_content2 == '建议退款':
                new = MIMEMultipart("mixed")
                body = MIMEMultipart("alternative")
                body.attach( MIMEText("reply body text", "plain") )
                body.attach( MIMEText(html_content, "html") )
                new.attach(body)
                
                new["Message-ID"] = email.utils.make_msgid()
                new["In-Reply-To"] = mail_id
                new["References"] = mail_id
                new["Subject"] = "回复: "+ subject
                new["To"] = mail_from
                new["From"] = mail_to
                new["Cc"] = mail_cc
                
                new.attach( MIMEMessage(email_content) )
                
                print("发送回复邮件")
                flag = sender.sendmail(mail_from, [new["To"]], new.as_string())
                #print(flag)
            
                server.set_flags(massageList, b'\\Seen', silent=False)
                print("邮件:%s 已经设置为已读" % subject)
            else:
                pass
            
            pass
        else:
            pass
    else:
        pass
        
#退出登陆
server.logout()
sys.exit(0)

效果:

 

 

 

 

感叹:python真是胶水啊

标签:server,content,header,内容,mail,print,自动,企业邮箱,email
From: https://www.cnblogs.com/xuxiaobo/p/17070400.html

相关文章