python练习_邮件定时收取处理附件后发送结果

该脚本实现了一个自动化邮件处理系统,能够定时收取邮件,解析邮件内容和附件,尤其是针对特定主题的邮件。它能下载邮件附件,进行数据转换,然后将数据插入数据库。同时,系统会检查邮件是否已存在于数据库中,避免重复处理。此外,系统还具备发送邮件的功能,当满足特定条件时,将处理后的数据以附件形式通过邮件发送出去。整个流程涉及POP3和IMAP4协议、数据库操作、Excel数据处理及SMTP邮件发送等技术。
摘要由CSDN通过智能技术生成

“”“第一步定时执行 ok
第二步收取邮件 ok
第三步数据转换 ok
第四步邮件派发 ok”""

-- coding: utf-8 --

import time
import poplib,email,telnetlib
import datetime,time,sys,traceback
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr
import openpyxl
import pymysql
import imaplib
import smtplib #发送邮件模块
from email.mime.text import MIMEText #定义邮件内容
from email.mime.multipart import MIMEMultipart #用于传送附件
import os

#邮件下载
class down_email():

def __init__(self,user,password,eamil_server):
    # 输入邮件地址, 口令和POP3服务器地址:
    self.user = user
    # 此处密码是授权码,用于登录第三方邮件客户端
    self.password = password
    self.pop3_server = eamil_server

    print('self.user',self.user)
    print('self.pop3_server', self.pop3_server)

# 获得msg的编码
def guess_charset(self,msg):
    charset = msg.get_charset()
    if charset is None:
        content_type = msg.get('Content-Type', '').lower()
        pos = content_type.find('charset=')
        if pos >= 0:
            charset = content_type[pos + 8:].strip()
    return charset

#获取邮件内容
def get_content(self,msg):
    content=''
    content_type = msg.get_content_type()
    # print('content_type:',content_type)
    if content_type == 'text/plain': # or content_type == 'text/html'
        content = msg.get_payload(decode=True)
        charset = self.guess_charset(msg)
        if charset:
            content = content.decode(charset)
    return content

# 字符编码转换
# @staticmethod
def decode_str(self,str_in):
    value, charset = decode_header(str_in)[0]
    if charset:
        value = value.decode(charset)
    return value

# 解析邮件,获取附件
def get_att(self,msg_in, str_day):
    attachment_files = []
    for part in msg_in.walk():
        # 获取附件名称类型
        file_name = part.get_param("name")  # 如果是附件,这里就会取出附件的文件名
        # file_name = part.get_filename() #获取file_name的第2中方法
        # contType = part.get_content_type()
        if file_name:
            h = email.header.Header(file_name)
            # 对附件名称进行解码
            dh = email.header.decode_header(h)
            filename = dh[0][0]
            if dh[0][1]:
                # 将附件名称可读化
                filename = self.decode_str(str(filename, dh[0][1]))
                # print(filename)
                # filename = filename.encode("utf-8")
            # 下载附件
            data = part.get_payload(decode=True)
            # 在指定目录下创建文件,注意二进制文件需要用wb模式打开
            #att_file = open('./客服数据/' + filename, 'wb')

            #提取文件名最后几个字符,获取邮件附件的格式

            if filename[-5:][0:1]=='.':
                filename_hz = filename[-5:]
            else:
                filename_hz = filename[-4:]

            #将经分下载附件保存到本地
            att_file = open('./客服数据/经分数据导出测试表' + filename_hz, 'wb')
            att_file.write(data)  # 保存附件
            att_file.close()
            attachment_files.append(filename)
        else:
            # 不是附件,是文本内容
            print(self.get_content(part))
            # # 如果ture的话内容是没用的
            # if not part.is_multipart():
            #     # 解码出文本内容,直接输出来就可以了。
            #     print(part.get_payload(decode=True).decode('utf-8'))

    return attachment_files

def mysql_execute(self, in_sql, leixing):
    # 登录数据库
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='szc', password='szcNSP850219', database='szc_sql',
                           charset='utf8')
    # 得到一个可以执行SQL语句的光标对象
    cursor = conn.cursor()
    # 数据库执行导入的语句
    if leixing == '数量':
        # 反馈数量
        count = cursor.execute(in_sql)
    elif leixing == '单条':
        # 反馈单条
        cursor.execute(in_sql)
        count = cursor.fetchone()[0]
    elif leixing == '多条':
        # 反馈多条
        cursor.execute(in_sql)
        count = cursor.fetchall()
    elif leixing == '编辑':
        count = cursor.execute(in_sql)
        conn.commit()

    # 关闭光标对象
    cursor.close()
    # 关闭数据库连接
    conn.close()
    # 反馈
    return count

def parseHeader(self,message):
    # 解析邮件头部
    subject = message.get('subject')

    h = email.header.Header(subject)
    dh = email.header.decode_header(h)

    # subject = unicode(dh[0][0], dh[0][1]).encode('gb2312')
    subject = (dh[0][0], dh[0][1])

    return subject

def parseBody(self,message):
    # 解析邮件内容
    # 循环信件中的每一个mime的数据块
    for part in message.walk():
        # 这里要判断是否是multipart,是的话,里面的数据是一个message 列表
        if not part.is_multipart():
            charset = part.get_charset()
            # print 'charset: ', charset
            contenttype = part.get_content_type()
            # print 'content-type', contenttype
            name = part.get_param("name")  # 如果是附件,这里就会取出附件的文件名

            if name:  # 在这里额外添加中国移动的条件,judgedate(name)==1
                # 有附件
                # 下面的三行代码只是为了解码像 =?gbk?Q?=CF=E0=C6=AC.rar?=这样的文件名
                fh = email.header.Header(name)
                fdh = email.header.decode_header(fh)
                fname = fdh[0][0]
                #print('附件名:', fname)
                attach_data = part.get_payload(decode=True)  # 解码出附件数据,然后存储到文件中

                try:
                    f = open('./客服数据/经分数据导出测试表' + '.xlsx', 'wb')  # 注意一定要用wb来打开文件,因为附件一般都是二进制文件
                except:
                    print("附件名有非法字符,自动换一个")
                    f = open('./客服数据/经分数据导出测试表' + '.xlsx', 'wb')
                f.write(attach_data)
                f.close()
            else:
                # 不是附件,是文本内容
                print(part.get_payload(decode=True))  # 解码出文本内容,直接输出来就可以了。
                # pass
            # print '+'*60 # 用来区别各个部分的输出
    return str(fname).split("'")[1]
    # return str('kefushuju_'+time.strftime("%Y-%m-%d")+'.xlsx')

def run_ing(self):
    str_day = str(datetime.date.today())  # 日期赋值
    # 连接到POP3服务器,有些邮箱服务器需要ssl加密,可以使用poplib.POP3_SSL

    print('pop3_server', self.pop3_server[0:3])
    if self.pop3_server[0:3] == 'pop' or self.pop3_server[0:3] == 'POP':
        try:
            telnetlib.Telnet(self.pop3_server, 995)
            self.server = poplib.POP3_SSL(self.pop3_server, 995, timeout=50)
        except:
            time.sleep(50)
            self.server = poplib.POP3(self.pop3_server, 110, timeout=50)

        # server.set_debuglevel(1) # 可以打开或关闭调试信息
        # 打印POP3服务器的欢迎文字:
        print(self.server.getwelcome().decode('utf-8'))
        # 身份认证:
        self.server.user(self.user)
        self.server.pass_(self.password)
        # 返回邮件数量和占用空间:
        print('Messages: %s. Size: %s' % self.server.stat())
        # list()返回所有邮件的编号:
        resp, mails, octets = self.server.list()
        # 可以查看返回的列表类似[b'1 82923', b'2 2184', ...]
        print('邮件数据 mails:', mails)

        # 显示数量定义
        xianshi_cs = 0
        index = len(mails)
        for i in range(index, 0, -1):  # 倒序遍历邮件
            # for i in range(1, index + 1):# 顺序遍历邮件

            print('xianshi_cs:', xianshi_cs)
            # 显示数量定义 xianshi_cs 大于3就退出
            if xianshi_cs >= index:
                break
            xianshi_cs += 1

            print('显示:', i)
            resp, lines, octets = self.server.retr(i)
            # lines存储了邮件的原始文本的每一行,
            # 邮件的原始文本:
            msg_content = b'\r\n'.join(lines).decode('utf-8')
            # 解析邮件:
            msg = Parser().parsestr(msg_content)
            # 获取邮件的发件人,收件人, 抄送人,主题
            # hdr, addr = parseaddr(msg.get('From'))
            # From = self.decode_str(hdr)
            # hdr, addr = parseaddr(msg.get('To'))
            # To = self.decode_str(hdr)
            # 方法2:from or Form均可
            From = parseaddr(msg.get('from'))[1]
            To = parseaddr(msg.get('To'))[1]
            Cc = parseaddr(msg.get_all('Cc'))[1]  # 抄送人
            Subject = self.decode_str(msg.get('Subject'))

            # 获取邮件时间,格式化收件时间
            date1 = time.strptime(msg.get("Date")[0:24], '%a, %d %b %Y %H:%M:%S')
            # print('date1',date1)
            # 邮件时间格式转换
            date2 = time.strftime("%Y-%m-%d %H:%M:%S", date1)
            # print('date2', date2)

            # 只有标题是特定标题的才会执行
            if Subject == 'kfsj_mail_lcxh':
                print('邮件发起from:%s,邮件接收to:%s,Cc:%s,邮件标题:%s,date:%s' % (From, To, Cc, Subject, date2))
                attach_file = self.get_att(msg, str_day)
                print(attach_file)
                if date2 < str_day:
                    # break # 倒叙用break
                    continue  # 顺叙用continue
                else:
                    pass
            else:
                continue

        # 可以根据邮件索引号直接从服务器删除邮件:
        # self.server.dele(7)
        self.server.quit()
        return email_list

    else:
        try:
            telnetlib.Telnet(self.pop3_server, 993)
            self.server = imaplib.IMAP4_SSL(self.pop3_server, 993)
            print('imaplib.IMAP4_SSL')
        except:
            time.sleep(50)
            self.server = imaplib.IMAP4(self.pop3_server, 110)

        self.server.login(self.user, self.password)
        self.server.select()
        print('IMAP4_SSL')

        # 搜索邮件内容 shazhicheng@sd.chinamobile.com
        print(self.server.search)
        typ, data = self.server.search(None, 'ALL')
        print('typ', typ, 'data', data)
        # 搜索邮件内容

        data_a =str(data[0]).replace('b','').replace("'","").replace(' ','')
        count = len(data_a)

        pcount = 1
        subject_cs = 0
        for num in data[0].split()[::-1]:
            print('num', num)
            typ, data = self.server.fetch(num, '(RFC822)')
            text = data[0][1]
            message = email.message_from_bytes(text)  # 转换为email.message对象

            subject_a = str(self.parseHeader(message)[0])[2:16]
            print("标题", subject_a)
            yj_time = time.strptime(message.get('Date')[0:24], '%a, %d %b %Y %H:%M:%S')
            yj_date = time.strftime("%Y-%m-%d %H:%M:%S", yj_time)

            print("yj_date", yj_date)

            if subject_a == 'kfsj_mail_lcxh':
                # 检测是否已经发送过邮件,没有发送过的话才发送
                in_day = get_current_time()[0:8]
                sql = 'SELECT count(Email_title)  FROM customer_service_title where Email_title="%s" and in_time="%s"' % (
                    'kfsj_mail_lcxh', yj_date)
                num = mysql_execute(sql, '单条')
                print('数据库中该邮件是否已发送过', num)
                if num == 0:
                    subject_cs += 1
                    print('subject_cs',subject_cs)

                    f = self.parseBody(message)  # 返回值是为了把文件名返回主函数
                    if f.strip() != '':
                        fn = f
                        # 执行完将标题与时间计入数据库,以防下次再处理
                        sql = "insert into customer_service_title (Email_title,IN_TIME) values('%s','%s') " % (
                            'kfsj_mail_lcxh', yj_date)
                        num = mysql_execute(sql, '编辑')
                        print('insert into customer_service_title')
                    break
            print('subject_cs',subject_cs)
            data_b = range(2)
            print('data_b', data_b)

            print('pcount', pcount, 'count', count)
            if pcount > count:
                break
            pcount += 1

        self.server.close()
        self.server.logout()
        return data_b  # 返回值是为了把文件名返回主函数

#时间计算
def get_current_time():
ct = time.time()
local_time = time.localtime(ct)
data_head = time.strftime("%Y%m%d%H%M%S", local_time)
data_secs = abs(ct - round(ct)) * 1000
time_stamp = “%s%03d” % (data_head, data_secs)
return time_stamp

#邮件推送
def email_out(user,password,smtpserver,sender,receives):
in_time = get_current_time()

# 发送邮件主题和内容
subject = '客户投诉跟踪监控表[%s](测试)' % in_time[0:8]
content = '<html><h3>各位经理:</h3>' \
          '<h3>      附件是本周更新的客户投诉指标跟踪表(测试),请收阅。</h3>' \
          '<h3 style="color:red">客服数据模板测试!</h3></html>'
# 构造附件内容:定义附件,构造附件内容
send_file = open(r".\客服数据\客服数据导入模板.xlsx", 'rb').read()  # 'rb'表示r读取,b表示二进制方式读取
att = MIMEText(send_file, 'base64', 'utf-8')  # 调用传送附件模块,传送附件
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment;filename="customer_service.xlsx"'  # 附件描述外层要用单引号
# 构建发送与接收信息
msgRoot = MIMEMultipart()  # 发送附件的方法定义为一个变量
msgRoot.attach(MIMEText(content, 'html', 'utf-8'))  # 发送附件的方法中嵌套发送正文的方法
msgRoot['subject'] = subject
msgRoot['From'] = sender
#msgRoot['From'] ='13605330822@139.com' #可以设置接收者看到的发送人邮箱
msgRoot['To'] = ','.join(receives)
msgRoot.attach(att)  # 添加附件到正文中
# SSL协议端口号要使用465
smtp = smtplib.SMTP_SSL(smtpserver, 465)
# HELO 向服务器标识用户身份
smtp.helo(smtpserver)
# 服务器返回结果确认
smtp.ehlo(smtpserver)
# 登录邮箱服务器用户名和密码
smtp.login(user, password)
#print("Start send email...")
smtp.sendmail(sender, receives, msgRoot.as_string())
smtp.quit()
return "Send End!"

#邮箱配置文件
def email_type():
wb = openpyxl.load_workbook(’./客服数据/邮箱配置文件.xlsx’)
ws = wb.active
minr = ws.min_row
minc = ws.min_column
maxr = ws.max_row
maxc = ws.max_column
# 数据库内容
print(minr, minc, maxr, maxc)
rngs = ws.iter_rows(min_row=minr, min_col=minc,
max_row=maxr, max_col=maxc)
row_cs = 0
for row in rngs:
if row_cs == 1:
value = [c.value for c in row]
user = value[0]
password = value[1]
eamil_server = value[2]
smtpserver = value[3]
receives = value[4].replace(" “,”").replace("[","").replace("]","").replace("’","").split(",")
#print(‘文字:’, receives)

    row_cs += 1
return user,password,eamil_server,smtpserver,receives

def mysql_execute(in_sql, leixing):
# 登录数据库
conn = pymysql.connect(host=‘127.0.0.1’, port=3306, user=‘szc’, password=‘szcNSP850219’, database=‘szc_sql’,
charset=‘utf8’)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
# 数据库执行导入的语句
if leixing == ‘数量’:
# 反馈数量
count = cursor.execute(in_sql)
elif leixing == ‘单条’:
# 反馈单条
cursor.execute(in_sql)
count = cursor.fetchone()[0]
elif leixing == ‘多条’:
# 反馈多条
cursor.execute(in_sql)
count = cursor.fetchall()
elif leixing == ‘编辑’:
count = cursor.execute(in_sql)
conn.commit()

# 关闭光标对象
cursor.close()
# 关闭数据库连接
conn.close()
# 反馈
return count

#后台excel数据处理
def seek_place(sheet,neirong,date,zhibiao,paiming,yuejun,yuedu,defen):
in_time = get_current_time()
in_yue = in_time[4:6]
#print(‘in_time’,in_time,in_yue)

#打开导入模板
mb_wb = openpyxl.load_workbook('./客服数据/客服数据导入模板.xlsx')

#print('查找内容:', sheet, neirong, date, zhibiao, paiming, yuejun, yuedu, defen)
# 表1 月份单元格列号,i这个不需要所以对应0
s1_yue_lie = ['I','J','K','L','M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U']
# 表2 月份单元格列号,i这个不需要所以对应0
s2_yue_lie = ['F','G','H','I','J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R']
# 表1 日期单元格列号
s1_ri_lie = ['AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT',
             'AU', 'AV', 'AW', 'AX', 'AY', 'AZ', 'BA', 'BB', 'BC', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BK',
             'BL', 'BM', 'BN', 'BO']
# 表2 日期单元格列号
s2_ri_lie = ['X', 'Y', 'Z', 'AA', 'AB', 'AC','AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT',
             'AU', 'AV', 'AW', 'AX', 'AY', 'AZ', 'BA', 'BB', 'BC', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI']

s1_ri = ['0000']
if in_yue == '01':
    old_yue = '12'
else:
    old_yue = str(int(in_yue) - 1)

for i in (old_yue, in_yue):
    if i == old_yue:
        for a in (26, 27, 28, 29, 30, 31):
            s1_ri.append(i + str(a))
    else:
        for a in range(32):
            if a == 0:
                continue
            if len(str(a)) == 1:
                a = '0' + str(a)
            s1_ri.append(i + str(a))
# 表1 日期表格
#print('s1_ri',s1_ri)

if sheet.startswith('S1'):


    mb_ws1 = mb_wb['经营业绩指标']
    mb_ws1_minr = mb_ws1.min_row
    mb_ws1_minc = mb_ws1.min_column
    mb_ws1_maxr = mb_ws1.max_row
    mb_ws1_maxc = mb_ws1.max_column
    mb_ws1_rngs = mb_ws1.iter_rows(min_row=mb_ws1_minr, min_col=mb_ws1_minc,
                        max_row=mb_ws1_maxr, max_col=mb_ws1_maxc)
    for row in mb_ws1_rngs:
        value = [c.value for c in row]
        value_str = str(value[2])
        if value_str == neirong:
            row_str = str(row[2])
            b = row_str.find('.')
            c = row_str.find('>')
            d = int(row_str[b + 1:c][1:])
            #print('行号', d)
            #长度判断
            if len(str(date)) == 6:
                yue_id = int(str(date)[4:])
                #print(str(date),s1_yue_lie[yue_id],d)
                lie_id = s1_yue_lie[yue_id]
                #print('行号:%s,列号:%s,数据:%s' % (d, lie_id, zhibiao))
                row_id = lie_id+str(d)
                mb_ws1[row_id]=zhibiao
                #print('行号:%s,列号:%s,排名:%s' % (d, 'V', paiming))
                row_id = 'V' + str(d)
                mb_ws1[row_id] = paiming
                #print('行号:%s,列号:%s,月均:%s' % (d, 'W', yuejun))
                row_id = 'W' + str(d)
                mb_ws1[row_id] = yuejun
                #print('行号:%s,列号:%s,排名:%s' % (d, 'X', yuedu))
                row_id = 'X' + str(d)
                mb_ws1[row_id] = yuedu
                #print('行号:%s,列号:%s,月均:%s' % (d, 'Y', defen))
                row_id = 'Y' + str(d)
                mb_ws1[row_id] = defen
            elif len(str(date)) == 8:
                day = str(date)[4:]
                day_id = s1_ri.index(day)
                lie_id = s1_ri_lie[day_id]
                #print('行号:%s,列号:%s,数据:%s' % (d, lie_id, zhibiao))
                row_id = lie_id + str(d)
                mb_ws1[row_id] = zhibiao
elif sheet.startswith('S2'):
    mb_ws1 = mb_wb['重点投诉指标']
    mb_ws1_minr = mb_ws1.min_row
    mb_ws1_minc = mb_ws1.min_column
    mb_ws1_maxr = mb_ws1.max_row
    mb_ws1_maxc = mb_ws1.max_column
    mb_ws1_rngs = mb_ws1.iter_rows(min_row=mb_ws1_minr, min_col=mb_ws1_minc,
                                   max_row=mb_ws1_maxr, max_col=mb_ws1_maxc)
    for row in mb_ws1_rngs:
        value = [c.value for c in row]
        value_str = str(value[2])
        if value_str == neirong:
            row_str = str(row[2])
            b = row_str.find('.')
            c = row_str.find('>')
            d = int(row_str[b + 1:c][1:])
            #print('行号', d)
            # 长度判断
            if len(str(date)) == 6:
                yue_id = int(str(date)[4:])
                # print(str(date),s1_yue_lie[yue_id],d)
                lie_id = s2_yue_lie[yue_id]
                # print('行号:%s,列号:%s,数据:%s' % (d, lie_id, zhibiao))
                row_id = lie_id + str(d)
                mb_ws1[row_id] = zhibiao
                # print('行号:%s,列号:%s,排名:%s' % (d, 'V', paiming))
                row_id = 'S' + str(d)
                mb_ws1[row_id] = paiming
                # print('行号:%s,列号:%s,月均:%s' % (d, 'W', yuejun))
                row_id = 'T' + str(d)
                mb_ws1[row_id] = yuejun
                # print('行号:%s,列号:%s,排名:%s' % (d, 'X', yuedu))
                row_id = 'U' + str(d)
                mb_ws1[row_id] = yuedu
                # print('行号:%s,列号:%s,月均:%s' % (d, 'Y', defen))
                # row_id = 'Y' + str(d)
                # mb_ws1[row_id] = defen
            elif len(str(date)) == 8:
                day = str(date)[4:]
                day_id = s1_ri.index(day)
                lie_id = s2_ri_lie[day_id]
                #print('行号:%s,列号:%s,数据:%s' % (d, lie_id, zhibiao))
                row_id = lie_id + str(d)
                mb_ws1[row_id] = zhibiao
#执行完后保存
mb_wb.save('./客服数据/客服数据导入模板.xlsx')
#结束反馈
return '数据处理完成'

def excel_place():
for root, dirs, files in os.walk(r".\客服数据"):
for file in files:
# 处理邮箱附件 经分数据导出测试表 的数据
if file.replace(’.xlsx’, ‘’).replace(’.xls’, ‘’) == ‘经分数据导出测试表’:
# 将名称里带有 xlsx、xls的替换处理掉
file_name_jx = file.replace(’.xlsx’, ‘’).replace(’.xls’, ‘’)
print(‘开始导入:’ + file.replace(’.xlsx’, ‘’).replace(’.xls’, ‘’))
# 获取文件路径
# print(os.path.join(root, file))
file_name = os.path.join(root, file)
# 获取执行时间
in_time = time.strftime("%Y%m%d%H%M%S", time.localtime())
#print(in_time)

            # 提取excel文件首个打开页面内容
            wb = openpyxl.load_workbook(file_name)
            ws = wb.active
            minr = ws.min_row
            minc = ws.min_column
            maxr = ws.max_row
            maxc = ws.max_column
            # 数据库内容
            print(minr, minc, maxr, maxc)
            rngs = ws.iter_rows(min_row=minr, min_col=minc,
                                max_row=maxr, max_col=maxc)

            for row in rngs:
                # print(len(row)) #总列数
                # print([c.value for c in row]) # 该行每列数据
                value = [c.value for c in row]
                print('文字:', value)
                if str(value[0]).startswith('S1') or str(value[0]).startswith('S2'):
                    seek_place(value[0], value[1], value[2], value[3], value[4], value[5], value[6], value[7])
                else:
                    continue

if name == ‘main’:

#循环执行
while True:
    in_time = get_current_time()
    print('当前时间:',in_time)
    #邮件是否准备好
    is_ok =0
    # 如果当前时间在几点范围内 执行下面输出
    if in_time[8:10] in ('09', '10','11','12','13','14','15','16',
                         '17','18','19'):

        try:
            # 输入邮件地址, 口令和POP3服务器地址:
            user, password, eamil_server, smtpserver, receives = email_type()
            email_class=down_email(user=user,password=password,eamil_server=eamil_server)
            #接收邮件并判断是否有符合的结果
            email_list = email_class.run_ing()
            print('email_list:',email_list)
            if len(email_list) > 0:
                #接收邮件大于0 证明有邮件收取
                is_ok = 1

            # for email_a in email_list:
            #     print(email_a)
            #     email_title = email_a['邮件标题']
            #     in_time = email_a['date']

        except Exception as e:
            import traceback
            ex_msg = '{exception}'.format(exception=traceback.format_exc())
            print(ex_msg)
            # traceback.print_exc()
        # sys.stdout = origin
        # f.close()

    #定时发送,并且当天正确收取邮件,才会发送
    if in_time[8:10] in ('09', '10','11','12','13','14','15','16',
                         '17','18','19') and is_ok == 1 :
        # 提取当天日期
        in_day = get_current_time()[0:8]
        print('in_day', in_day)
        # 检测是否已经发送过邮件,没有发送过的话才发送
        sql = 'SELECT count(Email_title)  FROM customer_service_title where Email_title="%s" and in_time="%s"' % (
            '客服数据模板测试', in_day)
        num = mysql_execute(sql, '单条')
        print('数据库中该邮件是否已发送过', num)
        if num == 0:
            # excel处理函数
            excel_state = excel_place()
            # 打印处理结果
            print('excel处理函数:excel_state', excel_state)
            # 计算后邮件发送
            email_out(user=user, password=password, smtpserver=smtpserver, sender=user, receives=receives)
            # 执行完将标题与时间计入数据库,以防下次再处理
            sql = "insert into customer_service_title (Email_title,IN_TIME) values('%s','%s') " % (
                '客服数据模板测试', in_day)
            num = mysql_execute(sql, '编辑')
            print(in_day, '发送邮件完成')
        else:
            print(in_day, '已发送过邮件')

    #执行后延时60秒
    time.sleep(300)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值