公司的自動化發信一直是使用Gmail的SMTP方式,某次發現Gmail開始鎖使用此種方式一定要開啟的『低安全性應用程式存取權』一直自動被關閉。故只好換到Gmail API來發信,以下會介紹帳號如何設定開啟Gmail API發信權限、取得認證json檔案和python使用gmail api發信的example。

Step 1. Google Developer Console開啟Gmail API&設定服務帳號
開啟Gmail API的使用
https://console.developers.google.com

建立服務帳號

建立服務帳號時金鑰key請選擇json,建立完後會下載一份XXXXX.json的金鑰json檔,要保存好後續認證使用。
記住唯一識別碼

在服務帳號內頁,要記住唯一識別碼,後續設定安全性的時候會用到。
Step 2. 開啟Gmail寄信權限
https://accounts.google.com.tw
接下來進到G Suite的Admin頁面>安全性>進階設定>管理 API 用戶端存取權,這裡在用戶端名稱填上剛剛的唯一識別碼,API範圍的欄位填上scop,這邊會是寄信的scop,最後按下授權新增就行了。
https://www.googleapis.com/auth/gmail.send

Step 3. Gmail API Python Example
安裝相關套件
$ pip install google-api-python-client google-auth google-auth-httplib2 google-auth-oauthlib
Python Example
import base64 from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email.header import Header from email import encoders from mimetypes import guess_type from os.path import join from googleapiclient.discovery import build from google.oauth2 import service_account SCOPES = ['https://www.googleapis.com/auth/gmail.send'] def gen_mail(send_from, send_to, subject, html, plain): msg = MIMEMultipart('mixed') msg['From'] = send_from msg['Subject'] = Header(subject, 'utf-8') msg['To'] = send_to if html: part1 = MIMEText(html, 'html', 'utf-8') msg.attach(part1) else: part2 = MIMEText(plain, 'plain', 'utf-8') msg.attach(part2) return msg def send_mail(send_from, msg): credentials = service_account.Credentials.from_service_account_file( f'{path}/{key_file}.json', scopes=SCOPES) delegated_credentials = credentials.with_subject("[email protected]") service = build('gmail', 'v1', credentials=delegated_credentials) message = ( service.users().messages().send( userId=send_from, body={'raw': base64.urlsafe_b64encode(msg.as_string().encode()).decode() }).execute() ) print('Message Id: %s' % message['id']) if __name__ == '__main__': msg = gen_mail( "[email protected]", "[email protected],[email protected]", "subject", '''<strong>this is a testing text</strong>''', None ) send_mail("[email protected]", msg)
Example內範例了傳送html格式的email內容,在send_mail內是使用Gmail API驗證,並且將信寄出。