Python & GCP 学习笔记_Gmail API 操作

最近在一个偶然的情况下接触到 Gmail API
因此找了一个周末来好好研究一下该怎么操作他
以下是学习纪录,如果有错或是有更好的写法,欢迎留言讨论喔

简单目录

一、GCP设定教学以及取得 credentials.json

二、取得 token.json

三、利用 yagmail 寄送 email

四、参考资源

一、GCP 设定教学

首先,要使用和 google 各项服务相关的话必须到 Google_Cloud_Platform 建立帐户以及专案
,才可以取得各项服务相关的 API

(一)、Google Cloud Platform (GCP)

前往 这个网址 并登入 GCP

(二)、建立一个专案并启用 API

点选上方专案部分,可以建立 or 选择一个专案
http://img2.58codes.com/2024/20144024X5rL8lrlNy.jpg进入专案后,点选 "前往 API 总览" 并点选 启用 API 和服务
http://img2.58codes.com/2024/20144024wpiNo13Q8T.jpg
http://img2.58codes.com/2024/201440243M8ex5Pxu3.jpg之后会进入到一个搜寻页面,搜寻 gmail api 点选进入后选择启用
http://img2.58codes.com/2024/20144024RkLsdZCC7u.jpg
http://img2.58codes.com/2024/20144024kQbaY60Zuh.jpg

(三)、取得凭证和 credentials.json

回到主页并选取左上方的三条线,并选择 "API 和服务"
http://img2.58codes.com/2024/20144024Js9zSRT5K3.jpg进入后选择凭证
http://img2.58codes.com/2024/20144024DiOztDjjqC.jpg点选上方的建立凭证,并依序建立 "API 金钥" 以及 "OAuth 2.0 用户端 ID"
http://img2.58codes.com/2024/20144024cD7erXyCIG.jpg点选 "OAuth 2.0 用户端 ID" "动作" 栏位下方的下载按钮,会挑出一个弹跳视窗,接着点选 下载 JSON
http://img2.58codes.com/2024/20144024zqHJOKB1pF.jpg
http://img2.58codes.com/2024/20144024AvomgR0DdV.jpg将下载下来的档案命名为 credentials.json,留着备用

二、取得 token.json

以下操作皆于 pycharm 底下进行,事前需要先建立一个空专案

(一)、安装必要套件

根据 官方文件 说明,
我们必须利用下面这个指令安装必要的套件
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

(二)、建立 "quickstart.py"

接着在专案目录底下建立一个名为 "quickstart.py" 的档案,并将下面的程式码複製贴上

from __future__ import print_functionimport os.pathfrom googleapiclient.discovery import buildfrom google_auth_oauthlib.flow import InstalledAppFlowfrom google.auth.transport.requests import Requestfrom google.oauth2.credentials import Credentials# If modifying these scopes, delete the file token.json.SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']def main():    """Shows basic usage of the Gmail API.    Lists the user's Gmail labels.    """    creds = None    # The file token.json stores the user's access and refresh tokens, and is    # created automatically when the authorization flow completes for the first    # time.    if os.path.exists('token.json'):        creds = Credentials.from_authorized_user_file('token.json', SCOPES)    # If there are no (valid) credentials available, let the user log in.    if not creds or not creds.valid:        if creds and creds.expired and creds.refresh_token:            creds.refresh(Request())        else:            flow = InstalledAppFlow.from_client_secrets_file(                'credentials.json', SCOPES)            creds = flow.run_local_server(port=0)        # Save the credentials for the next run        with open('token.json', 'w') as token:            token.write(creds.to_json())    service = build('gmail', 'v1', credentials=creds)    # Call the Gmail API    results = service.users().labels().list(userId='me').execute()    labels = results.get('labels', [])    if not labels:        print('No labels found.')    else:        print('Labels:')        for label in labels:            print(label['name'])if __name__ == '__main__':    main()

(三)、修改 SCOPES

由于一些权限问题,会造成 mail 无法寄送,因此我们需要替换下面这行程式码

before:
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']after:
SCOPES = ['https://mail.google.com/']

(四)、移动 credentials.json

接着将刚刚备用的 credentials.json 档案移动到专案资料夹底下
http://img2.58codes.com/2024/20144024CBSbBhbH0H.jpg

(五)、执行 quickstart.py

接着执行 "quickstart.py" 会自动跳出浏览器视窗要你选择 or 登入帐号
http://img2.58codes.com/2024/20144024gfhoFz3ODy.jpg
接着按照流程点选继续 -> 继续,全部结束后会跳出文字题是可以关闭视窗
http://img2.58codes.com/2024/20144024Fm68ktJYAZ.jpg
回到专案资料夹内你会发现专案资料夹内多了一个 "token.json" 的档案
http://img2.58codes.com/2024/20144024UaHR2McrvW.jpg
到这边为止所有的设定就完成成了,接下来要开始正式寄信了!!

三、利用 yagmail 寄送 email

如果按照官方文件的步骤寄出一封 mail 会需要许多的步骤,笔者这边找到一个叫 yagmail 的套件
,可以协助我们处理 mail 的寄送

(一)、安装 yagmail

pip install yagmail[all]

(二)、建立一个新的 python 档案

建立一个新的 python 档案,并将以下程式码複製进去

import yagmailfile = ['runtime.txt', 'debug.log']  # 传送多个档案 以list型态yag = yagmail.SMTP("xxx@gmail.com", oauth2_file="credentials.json")yag.send(    to="xxxx@gmail.com",     subject="subject",    contents="contents",    attachments=file)
解释:file 的部分取决于有没有要传送档案,如果只有一个,则直接指定档案路径,若有多个,可以用 list 包起来yagmail.SMTP,第一个参数为 mail 的撰写者, oauth2_file 则是前面有提到过的 credentials.json 档案yag.send(),to 参数为 mail 的收件者,同样如果要指定多个收件者,可使用 list 包起来其他三个参数分别为,主旨、内容、附件

(三)、寄送 email

将上面的档案编辑好后,就可以执行该档案来实际寄送 email 了,如果是第一次寄送会需要进行下面的步骤

terminal 会提示你输入你的 email
http://img2.58codes.com/2024/20144024CJIAgJrVDW.jpg输入之后会秀出一段网址,请点击该网址并选择 or 登入帐户,并依序案两次继续
http://img2.58codes.com/2024/20144024bL851W9dJe.jpg取得验证码,并複製
http://img2.58codes.com/2024/201440243NegtcuOLI.jpg回到 terminal 中贴上验证码在 "Enter verification code" 的后面并 Enter寄信成功
备注: 目前测试下来是每个专案只需要进行上述步骤一次,后续都不需要再进行

四、参考资源

Gmail API 官方文件yagmail 教学文章yagmail 套件

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章