要使用本地主机的Gmail API,你需要遵循以下步骤:
创建一个Google Cloud项目并启用Gmail API:
创建OAuth 2.0凭据:
安装所需的库和依赖项:
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
使用示例代码: 下面是一个使用Gmail API发送电子邮件的示例代码:
import os
import base64
import google.auth
import google.auth.transport.requests
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
# 加载凭据
credentials, project = google.auth.default()
credentials = Credentials.from_authorized_user_file('credentials.json')
# 创建Gmail API客户端
service = build('gmail', 'v1', credentials=credentials)
# 构建电子邮件消息
message = {
'raw': base64.urlsafe_b64encode('From: sender@gmail.com\nTo: recipient@gmail.com\nSubject: Test email\n\nHello, this is a test email!'.encode('utf-8')).decode('utf-8')
}
# 发送电子邮件
response = service.users().messages().send(userId='me', body=message).execute()
print('Email sent.')
注意:在上述代码中,你需要将credentials.json
替换为你的凭据文件路径,并将sender@gmail.com
和recipient@gmail.com
替换为你的发件人和收件人电子邮件地址。
希望这可以帮助你使用本地主机的Gmail API。
上一篇:本地主机的CORS问题?
下一篇:本地主机的含义: dsf