【问题标题】:How can I send email using python with google workspace如何使用 python 和谷歌工作区发送电子邮件
【发布时间】:2022-07-11 21:33:18
【问题描述】:

我刚刚注册了 Google 工作区业务启动器,因为人们提出了很多建议,我想知道使用 Django 通过我的后端 API 发送电子邮件的可能性有多大,我在网上搜索过但没有全面或直接,尝试联系他们的支持,但不可用。 提前致谢

【问题讨论】:

  • 试试这个delegation#python 将 admin sdk 换成 gmail api,然后用它来发送您的电子邮件。

标签: django gmail google-workspace django-email google-gsuite


【解决方案1】:
from google.oauth2 import service_account

SERVICE_ACCOUNT_FILE= 'path_to_your_json_credential_file'
DELEGATE='youremail@yourcompany.com'  # The service account will impersonate this user. The service account must have proper admin privileges in G Workspace.
TARGET='yourcompany.com'  # Service account wants to access data from this.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'] # ... or whatever scope(s) you need for your purpose

def connect_to_gmail():
    credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    credentials_delegated = credentials.with_subject(DELEGATE)
    gmail = build('gmail', 'v1', credentials=credentials_delegated)

    # do whatever you need with it, check the exemple below :
    new_msg_history_lst = gmail.users().history().list(userId='me',maxResults=3, startHistoryId='1', labelId='INBOX').execute()
    print(new_msg_history_lst)

要使上述代码正常工作,它的前提是:

  • 该帐户是 google 工作区帐户
  • 您已创建服务帐户,为其创建密钥,并将其下载为 json
  • 您已为服务帐户添加了域范围委派,并至少添加了与上述相同的范围

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    • 2020-09-07
    • 2018-03-05
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多