美文网首页
python2.7定时下载邮箱内的附件

python2.7定时下载邮箱内的附件

作者: 从何说起_b2be | 来源:发表于2018-09-05 15:06 被阅读0次

    `

    !/usr/bin/env python

    -- coding: utf-8 --

    @Time : 2018/9/5 9:09

    @Author : Zeta He

    @Site :

    @File : timer_email.py

    @Software: PyCharm Community Edition

    import poplib
    import email
    from email.parser import Parser
    from email.header import decode_header
    from email.utils import parseaddr
    import datetime

    def decode_str(s):
    value, charset = decode_header(s)[0]
    if charset:
    value = value.decode(charset)
    return value

    用于解析邮件名称

    def get_email_headers(msg):
    # 邮件的From, To, Subject存在于根对象上:
    headers = {}
    for header in ['From', 'To', 'Subject', 'Date']:
    value = msg.get(header, '')
    if value:
    if header == 'Date':
    headers['date'] = value
    if header == 'Subject':
    # 需要解码Subject字符串:
    subject = decode_str(value)
    headers['subject'] = subject
    else:
    # 需要解码Email地址:
    hdr, addr = parseaddr(value)
    name = decode_str(hdr)
    value = u'%s <%s>' % (name, addr)
    if header == 'From':
    from_address = value
    headers['from'] = from_address
    else:
    to_address = value
    headers['to'] = to_address
    content_type = msg.get_content_type()
    print 'head content_type: ', content_type
    return headers

    def get_email_content(message, base_save_path):
    # 只取来自于胡冬伟的邮件
    #print len(message)
    #获取发件人信息
    From =get_email_headers(message)['from']
    #判断是否来自于hudongwei@china-invs.cn
    if "hudongwei@china-invs.cn" not in From:
    return
    j = 0
    attachment_files = []
    for part in message.walk():
    print len(part)
    j = j + 1
    file_name = part.get_filename()
    # 保存来自hudongwei@china-invs.cn的附件
    if file_name: # Attachment
    fname=decode_str(file_name)
    att_file = open("%s%s"%(base_save_path,fname), 'wb')
    data = part.get_payload(decode=True)
    att_file.write(data)
    att_file.close()
    return attachment_files

    连接邮箱

    def conn_email():
    # 输入邮件地址, 口令和POP3服务器地址:
    email = 'zeta_he'
    password = '*****'
    pop3_server = 'mail.china-invs.cn'
    # 连接到POP3服务器:
    server = poplib.POP3(pop3_server)
    # 身份认证:
    server.user(email)
    server.pass_(password)
    # stat()返回邮件数量和占用空间:
    print('Messages: %s. Size: %s' % server.stat())
    # list()返回所有邮件的编号:
    resp, mails, octets = server.list()
    # 考虑到数据量庞大仅获取第1-20封邮件
    messages = []
    for i in range(len(mails) - 20, len(mails) - 1):
    messages.append(server.retr(i))
    # mssg[1]为内容正文,加个回车换行把逗号分隔符,链接成一个完整字符串
    messages = ["\n".join(mssg[1]) for mssg in messages]
    # 转化为邮件实例的Message对象
    messages = [Parser().parsestr(mssg) for mssg in messages]
    print len(mails) - 20
    print u'---------- 获取邮件内容(附件) ----------'
    base_save_path = 'D:/email_files/'
    for i in range(0, len(messages)):
    msg = messages[i]
    get_email_content(msg, base_save_path)
    print u'---------- 附件已保存至D:/email_files/ ----------'
    # 关闭连接:
    server.quit()

    def timerRun(sched_Timer):
    loopflag = 0
    while True:
    now = datetime.datetime.now()
    if now==sched_Timer:
    conn_email()
    loopflag=1
    else:
    if loopflag==1:
    sched_Timer=sched_Timer+datetime.timedelta(minutes=1)
    loopflag=0

    if name == 'main':
    sched_time = datetime.datetime(2018, 9, 5, 9, 30, 0)
    print 'run the timer task at {0}'.format(sched_time)
    timerRun(sched_time)

    `

    相关文章

      网友评论

          本文标题:python2.7定时下载邮箱内的附件

          本文链接:https://www.haomeiwen.com/subject/kmpawftx.html