[問題] Python 2.7 + Django透過Gmail API發信

作者: dppman (*^o^*)   2018-07-20 17:45:50
請問一下,
已經在Google API Console啟用了Gmail API, 希望透過OAauth認證來呼叫
Gmail API發信,已經爬文寫了下列的Code但還是沒成功, API console沒看到
access log :<
不知道版上前輩是否可以指點一下? Thanks
參考的code :https://gist.github.com/grunsab/e427365bf303145a01b3
環境是EC2 Ubuntu 4.4.0-1062-aws
==============================================
from __future__ import print_function
import httplib2
import os
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
import base64
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import mimetypes
import os
from apiclient import errors
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except:
flags = None
SCOPES = 'https://www.googleapis.com/auth/gmail.send'
##
# 從API Consloe的OAuth 2.0 用戶端 ID內選下載json對嗎?並更名為
# client_secret.json ?
# 因為Consloe內也沒有其他json可以下載
##
CLIENT_SECRET_FILE = 'client_secret.json'
#
# APPLICATION_NAME = 是Google API Console內的OAuth 2.0 用戶端 ID?
#
APPLICATION_NAME = 'mygmailapp'
##
# 呼叫 get_credentials()應該是要把get到的credential,
# 存到~/.credentials/gmail-python-quickstart.json 對嗎?
##
def get_credentials():
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 = 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
=========================================================================
作者: mychiux413 (小邱)   2018-07-24 22:26:00
他有開出瀏覽器叫你登入嗎?如果沒有,可能是json檔載錯或是貼個錯誤信息比較好懂,也有可能是API沒開通json檔不能選server用的,會打不開網頁,雖然忘了怎麼做但關鍵可能在那邊,另外一個可能是信件超過3MB會出現pipe broken之類的bug,要把容量壓小試試看全部設定完後只需要留gmail***.json這個檔就夠了

Links booklink

Contact Us: admin [ a t ] ucptt.com