python 3.x - Gmail api获取标题和发件人

时间:2017-01-20 13:47:48

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

我刚刚开始使用Gmail API,并按照Oauth2.0教程获取了autherisation代码。到目前为止我的代码是:

from oauth2client import client
import webbrowser
import httplib2

flow = client.flow_from_clientsecrets(
    'client_secrets.json',
    scope='https://www.googleapis.com/auth/gmail.readonly',
    redirect_uri='urn:ietf:wg:oauth:2.0:oob')

auth_uri = flow.step1_get_authorize_url()
webbrowser.open_new(auth_uri)

authcode = input("Enter auth code: ")

credentials = flow.step2_exchange(authcode)
http_auth = credentials.authorize(httplib2.Http())

我想通过提出以这种格式获取最新未读邮件的主题和发件人的请求来测试API:

#pseudocode
get latestMessage
if latestMessage.read == True:
    print("you have no unread messages)
else:
    print("you have a new email: " + latestMessage.subject + " from" + latestmessage.sender)

2 个答案:

答案 0 :(得分:1)

如上所述here,如果您想要标题为“收件人”,“收件人”,“主题”,则可以调用messages.get(format=METADATA),或者查看您正在使用的语言。您可以查看文档中的example

Returns:
    An object containing a base64url encoded email object.
  """

  message = MIMEText(message_text)
  message['to'] = to
  message['from'] = sender
  message['subject'] = subject
  return {'raw': base64.urlsafe_b64encode(message.as_string())}

您还可以在此SO question中查看如何获取电子邮件发件人的答案。

答案 1 :(得分:0)

我创建了一个模板脚本(Python 3.5)来访问Gmail并获取诸如日期,主题,代码段,发件人电子邮件和邮件正文之类的参数。

您可以在我的github存储库中查看它,并根据需要进行分叉。链接为https://github.com/abhishekchhibber/Gmail-Api-through-Python