如何正確設置發送電子郵件的Gmail API腳本?CRON Node.js Gmail API腳本
我即將使用this method,我開始從this quickstart指南構建我的腳本。
是否有其他方法可以在不使用OAuth 2驗證的情況下執行此操作?或者一種驗證一次的方法?
如何正確設置發送電子郵件的Gmail API腳本?CRON Node.js Gmail API腳本
我即將使用this method,我開始從this quickstart指南構建我的腳本。
是否有其他方法可以在不使用OAuth 2驗證的情況下執行此操作?或者一種驗證一次的方法?
我找到解決方案使用智威湯遜授權的OAuth2。 您需要擁有管理員帳戶才能創建域範圍的授權服務帳戶。然後在開發者控制檯中,您需要下載作爲憑據加載的服務密鑰JSON文件。
首先取像這樣所有用戶:(這裏你需要使用帳戶admin目錄權限)
const google = require('googleapis');
const gmail = google.gmail('v1');
const directory = google.admin('directory_v1');
const scopes = [
'https://www.googleapis.com/auth/gmail.readonly',
'https://www.googleapis.com/auth/admin.directory.user.readonly'
];
const key = require('./service_key.json');
var authClient = new google.auth.JWT(
key.client_email,
key,
key.private_key,
scopes,
"[email protected]"
);
authClient.authorize(function(err, tokens){
if (err) {
console.log(err);
return;
}
directory.users.list(
{
auth: authClient,
customer: 'my_customer',
maxResults: 250,
orderBy: 'email'
}, (err, resp) => {
if (err) {
console.log(err);
return;
}
console.log(resp);
});
});
然後,你需要獲取主題列表(100個請求(頁))。並且對於每個線程對象,您需要爲完整線程調用get方法。以用戶身份使用Gmail API授權時,您需要從中提取電子郵件。在請求userId
使用價值'me'
。
那麼,在將Gmail APi與您的應用程序一起使用時,您需要使用OAuth 2.0,因爲所有對Gmail API的請求都必須由經過身份驗證的用戶授權。如果您注意到quickstart,那麼您需要創建憑證/ Outh客戶端ID來使此API有效。
欲瞭解更多信息,還有另一種方式authorize your app with Gmail。您可以在Google+ Sign-in的幫助下爲您的應用提供「使用Google登錄」身份驗證方法。
在向GMail請求授權時,OAuth 2.0會提供一個訪問令牌和一個刷新令牌。爲了避免每次都進行驗證,請存儲訪問令牌。使用刷新令牌在新訪問令牌過期後(訪問令牌每隔一小時過期)獲取一次。
閱讀這裏這個過程:https://developers.google.com/identity/protocols/OAuth2
我即將從服務器執行該腳本作爲CRON。基本上它應該以特定的時間間隔自動執行。是否可以爲我的電子郵件使用域範圍委派並避免我們公司域內其他帳戶的身份驗證? – Kunok