python 编写快速脚本,用于阅读我们的许多公司电子邮件,以获取Kidkraft的库存状态更新,然后下载附带的xlsx文件f

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 编写快速脚本,用于阅读我们的许多公司电子邮件,以获取Kidkraft的库存状态更新,然后下载附带的xlsx文件f相关的知识,希望对你有一定的参考价值。

#!/usr/bin/env python

import email
import imaplib
import os
import sys

detach_dir = '.' # directory where to save attachments (default: current)

files = os.listdir('.')

for f in files:
    if os.path.splitext(f)[1] == '.xlsx':
        print("Removing: %s" % f)
        os.remove(f)

user = 'USER'
pwd = 'PASS'

# connecting to the gmail imap server
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user,pwd)
m.select()

resp, items = m.search(None, '(HEADER Subject "Stock Status")') #Search for  "Stcok Status" in the subject
items = items[0].split() 
items.reverse() # Get the latest first
items = items[:1]

for emailid in items:
    resp, data = m.fetch(emailid, "(RFC822)")
    email_body = data[0][1]
    mail = email.message_from_string(email_body)

    #Check if any attachments at all
    if mail.get_content_maintype() != 'multipart':
        print 'No attachment'
        continue

print "["+mail["From"]+"] :" + mail["Subject"]

for part in mail.walk():
    if part.get_content_maintype() == 'multipart':
        continue

    # part an attachment ?
    if part.get('Content-Disposition') is None:
        continue

filename = part.get_filename()
counter = 1

# if there is no filename, we create one with a counter to avoid duplicates
if not filename:
    filename = 'stock-%03d%s' % (counter, 'update')
    counter += 1

att_path = os.path.join(detach_dir, filename)

#Check if its already there
if not os.path.isfile(att_path) :
    fp = open(att_path, 'wb')
    fp.write(part.get_payload(decode=True))
    fp.close()

以上是关于python 编写快速脚本,用于阅读我们的许多公司电子邮件,以获取Kidkraft的库存状态更新,然后下载附带的xlsx文件f的主要内容,如果未能解决你的问题,请参考以下文章

python 快速和肮脏的查克诺里斯python脚本。用于我们的SVN post commit钩子。如果您没有请求库:yum install pytho

开发工具Python解释器安装配置教程

简介

python盛行的时代, 我还是爱perl~

编写快速安全 Bash 脚本的建议 | 翻译

Python 基础语法