最近在一个偶然的情况下接触到 Gmail API
因此找了一个周末来好好研究一下该怎麽操作他
以下是学习纪录,如果有错或是有更好的写法,欢迎留言讨论喔
首先,要使用和 google 各项服务相关的话必须到 Google_Cloud_Platform 建立帐户以及专案
,才可以取得各项服务相关的 API
前往 这个网址 并登入 GCP
以下操作皆於 pycharm 底下进行,事前需要先建立一个空专案
根据 官方文件 说明,
我们必须利用下面这个指令安装必要的套件
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
接着在专案目录底下建立一个名为 "quickstart.py" 的档案,并将下面的程序码复制贴上
from __future__ import print_function
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from 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()
由於一些权限问题,会造成 mail 无法寄送,因此我们需要替换下面这行程序码
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
SCOPES = ['https://mail.google.com/']
接着将刚刚备用的 credentials.json 档案移动到专案资料夹底下
接着执行 "quickstart.py" 会自动跳出浏览器视窗要你选择 or 登入帐号
接着按照流程点选继续 -> 继续,全部结束後会跳出文字题是可以关闭视窗
回到专案资料夹内你会发现专案资料夹内多了一个 "token.json" 的档案
到这边为止所有的设定就完成成了,接下来要开始正式寄信了!!
如果按照官方文件的步骤寄出一封 mail 会需要许多的步骤,笔者这边找到一个叫 yagmail 的套件
,可以协助我们处理 mail 的寄送
pip install yagmail[all]
建立一个新的 python 档案,并将以下程序码复制进去
import yagmail
file = ['runtime.txt', 'debug.log'] # 传送多个档案 以list型态
yag = yagmail.SMTP("[email protected]", oauth2_file="credentials.json")
yag.send(
to="[email protected]",
subject="subject",
contents="contents",
attachments=file
)
将上面的档案编辑好後,就可以执行该档案来实际寄送 email 了,如果是第一次寄送会需要进行下面的步骤
What is an SMTP Server? SMTP 全名为Simple Mail Transf...
接续 Day 10 时钟同步和精度 (CLock Synchronization and Accu...
在经过一个月的学习之後,操作上只是理解有非常多可以客制化的部分,难免会想资讯图像化的部分到底可以炫技...
如标题,这篇想教大家如何自己手动分割硬碟 Windows有C槽、D槽、E槽……等,但linux没有w...
前言 今天要接续DataFrame的介绍 这篇文章会分成两个部分: 资料的删除 资料的新增 会利用k...