根據你下面所說的關於想用gmail編寫命令系統,我寫了一個簡單的腳本來使用IMAP來完成這個任務。我認爲這可能比嘗試爲單個用戶使用Google API更簡單,除非您只是想爲此練習做這些工作。
import imaplib, logging
from time import sleep
USERNAME = 'YOUR_USERNAME_HERE' # For gmail, this is your full email address.
PASSWORD = 'YOUR_PASSWORD_HERE'
CHECK_DELAY = 60 # In seconds
LOGGING_FORMAT = '%(asctime)s %(message)s'
logging.basicConfig(filename='imapTest.log', format=LOGGING_FORMAT, level=logging.INFO)
logging.info("Connecting to IMAP server...")
imap = imaplib.IMAP4_SSL('imap.gmail.com')
imap.login(USERNAME, PASSWORD)
logging.info("Connected to IMAP server.")
def get_command_messages():
logging.info("Checking for new commands.")
imap.check()
# Search the inbox (server-side) for messages containing the subject 'COMMAND' and which are from you.
# Substitute USERNAME below for the sending email address if it differs.
typ, data = imap.search(None, '(FROM "%s" SUBJECT "COMMAND")' %(USERNAME))
return data[0]
def delete_messages(message_nums):
logging.info("Deleting old commands.")
for message in message_nums.split():
imap.store(message, '+FLAGS', '\\DELETED')
imap.expunge()
# Select the inbox
imap.select()
# Delete any messages left over that match commands, so we are starting 'clean'.
# This probably isn't the nicest way to do this, but saves checking the DATE header.
message_nums = get_command_messages()
delete_messages(message_nums)
try:
while True:
sleep(CHECK_DELAY)
# Get the message body and sent time. Use BODY.PEEK instead of BODY if you don't want to mark the message as read, but we're deleting it anyway below.
message_nums = get_command_messages()
if message_nums:
# search returns space-separated message IDs, but we need them comma-separated for fetch.
typ, messages = imap.fetch(message_nums.replace(' ', ','), '(BODY[TEXT])')
logging.info("Found %d commands" %(len(messages[0])))
for message in messages[0]:
# You now have the message body in the message variable.
# From here, you can check against it to perform commands, e.g:
if 'shutdown' in message:
print("I got a shutdown command!")
# Do stuff
delete_messages(message_nums)
finally:
try:
imap.close()
except:
pass
imap.logout()
如果你在使用Gmail的API集,但是,谷歌強烈建議您使用他們現有的Python庫,而不是試圖做的完全認證等你自己,你似乎是。因此,它應該 - 或多或少 - 是用相關的Gmail API取代上述的imap電話的一種情況。
我要說的是它在谷歌開發者網站上說的,除了需要使用RSASHA256簽名之外,它沒有提供很多信息。你有解釋的鏈接嗎? – Aflake 2014-08-30 18:23:35
那麼[Google的Python庫](https://developers.google.com/api-client-library/python/guide/aaa_oauth)對您有什麼用處?如果是這樣,該頁面將解釋如何使用它,並提供一個鏈接,以便只下載oauth客戶端,如果這是您所需要的。特別是,我懷疑''flow_from_clientsecrets()'方法將是你所需要的。除此之外,我不確定如果不知道您想要使用特定的Google API做什麼,我可以提供幫助。 – Kkelk 2014-08-31 00:16:00
我建立了一個服務帳戶,並且使用Gmail API計劃使用它來通過texting(電子郵件)橋接我的電腦和手機,並希望發送帶有諸如「command:reboot」之類文本的命令。這或多或少是一個腳本來幫助我與api和更大的項目進行交互。我的問題仍然與令牌請求有關,因爲我需要簽署我自己的JWT。 – Aflake 2014-08-31 02:27:38