Da die Dokumentausgabefunktion von Google Mail in Labs of Google Mail verschwunden ist, habe ich versucht, sie mithilfe der Google Mail-API von Google Apps problemlos mit Python zu schreiben.
Lesen Sie die folgende Dokumentation, um client_secret.json abzurufen.
Sie müssen lediglich die Anwendung definieren und herunterladen, damit Sie sie in etwa einer Minute ausführen können.
Installieren Sie den API-Client mit pip.
$ pip install --upgrade google-api-python-client
Im Fall des obigen Adressbeispiels wird die Ausgabe des Etiketts angezeigt. Fügen Sie daher den Code hinzu, um den Nachrichtentext abzurufen.
sample.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# from __future__ import print_function
import httplib2
import os
import base64
import logging
import traceback
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Gmail API Python Quickstart'
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(
credential_dir,
'gmail-python-quickstart.json'
)
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def extract_message(service, message):
try:
msg_obj = service.users().messages().get(userId='me', id=message['id'], format='raw').execute()
return base64.urlsafe_b64decode(msg_obj['raw'].encode('ASCII'))
except:
logging.error(traceback.format_exc())
def extract_message_body(service, message):
try:
email_str = extract_message(service, message)
subject_idx = email_str.find('Subject:')
body_idx = email_str[subject_idx:].find(os.linesep)
return email_str[subject_idx + body_idx:].strip()
except:
logging.error(traceback.format_exc())
def main():
"""Shows basic usage of the Gmail API.
Creates a Gmail API service object and outputs a list of label names
of the user's Gmail account.
"""
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)
results = service.users().messages().list(userId='me', q="").execute()
print results
messages = results.get('messages', [])
if not messages:
print 'No messages found.'
else:
print 'messages:'
for message in messages:
print 'message body: ', extract_message_body(service, message)
if __name__ == '__main__':
main()
Das Suchschlüsselwort wird als Zeichenfolge in q der Listenfunktion geworfen. Das Format entspricht der Google Mail-Suche.
Recommended Posts