Python脚本自动下载Gmail附件

时间:2019-04-10 10:56:52

标签: python python-3.x gmail-api

我希望python脚本定期(像每小时一样)自动下载gmail附件,这是一种.jpg格式,我尝试了此代码,但无法正常工作。

def get_csv_or_xl_attachments_from_msg_id(service, messageId):
    """returns a dict of all CSV attachments as pd.DataFrames
    in the email associated with `messageId`. The keys for the
    dictionary are the csv filenames"""
    msg = service.messages().get(userId='me', id=messageId).execute()
    msg_parts = msg.get('payload').get('parts')
    headers = msg.get('payload').get('headers')
    subject = [h['value'] for h in headers if h['name']=='Subject'][0]
    if not msg_parts:
        return []
    msg_parts = _flatten_nested_email_parts(msg_parts)
    att_parts = [p for p in msg_parts if p['mimeType'] in [
            CSV_MIME_TYPE, XLSX_MIME_TYPE]]
    types = [mime_type_to_dtype(p['mimeType']) for p in att_parts]
    filenames = [p['filename'] for p in att_parts]
    datas = [_get_attachment_from_part(service, messageId, p) for p in att_parts]
    dfs = [_convert_attachment_data_to_dataframe(d, t)
            for d, t in zip(datas, types)]
    return [{'emailsubject': subject, 'filename': f, 'data': d}
            for f, d in zip(filenames, dfs)]


def query_for_csv_or_xl_attachments(service, search_query):
    message_ids = query_for_message_ids(service, search_query)
    csvs = [] 
    for msg_id in message_ids:
        loop_csvs = get_csv_or_xl_attachments_from_msg_id(service, msg_id)
        csvs.extend(loop_csvs)
    return csvs

以上代码返回空白列表。即使我已发送带有附件的邮件。 有人可以帮我吗? 以下是整个存储库的URL。 https://github.com/robertdavidwest/google_api

0 个答案:

没有答案