Python 使用 Graph API 和 Office365-REST-Python-Client 发送电子邮件

标签 python azure microsoft-graph-api office365 microsoft-graph-mail

我正在尝试使用 Graph API 和 Python 发送电子邮件。我尝试使用图形资源管理器进行此操作,并且成功了。我找到了这个例子:https://github.com/vgrem/Office365-REST-Python-Client#working-with-outlook-api

from office365.graph_client import GraphClient

client = GraphClient(acquire_token_func)

client.me.send_mail(
    subject="Meet for lunch?",
    body="The new cafeteria is open.",
    to_recipients=["<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="67010609091e0327040809130814084908090a0e041508140801134904080a" rel="noreferrer noopener nofollow">[email protected]</a>"]
).execute_query()

这是我的代码:

import msal

dict_ = {'client_id': 'foo', 'secret': 'bar', 'tenant_id': 'etc'}

def acquire_token():
    authority_url = f'https://login.microsoftonline.com/{dict_["tenant_id"]}'
    app = msal.ConfidentialClientApplication(
        authority=authority_url,
        client_id=dict_["client_id"],
        client_credential=dict_["secret"]
    )
    token = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
    return token


from office365.graph_client import GraphClient

client = GraphClient(acquire_token)

client.me.send_mail(
    subject="Meet for lunch?",
    body="The new cafeteria is open.",
    to_recipients=['<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6c090003024201191f072c0f03011c0d0215420f0301" rel="noreferrer noopener nofollow">[email protected]</a>']
).execute_query()

尽管它与示例中的完全相同,但我仍然得到:

TypeError: send_mail() got an unexpected keyword argument 'subject'

您能帮我解决此问题或提供其他发送电子邮件的方式吗?

最佳答案

I agree with @user2250152, you need to change /me endpoint to client.users[<mail>].send_mail as you are using client credentials flow to get token.

我注册了一个 Azure AD 应用程序并授予了 Mail.Send 应用程序类型的权限:

enter image description here

就我而言,我使用下面的修改后的代码来使用 Graph API 和 Python 发送电子邮件:

import msal
import requests;

dict_ = {'client_id': 'appId', 'secret': 'secret', 'tenant_id': 'tenantId'}

def acquire_token():
    authority_url = f'https://login.microsoftonline.com/{dict_["tenant_id"]}'
    app = msal.ConfidentialClientApplication(
        authority=authority_url,
        client_id=dict_["client_id"],
        client_credential=dict_["secret"]
    )
    token = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
    return token

result = acquire_token()

if "access_token" in result:
    print("Access token created.",result["access_token"])

if "access_token" in result:
    endpoint = f'https://graph.microsoft.com/v1.0/users/userId/sendMail'
    toUserEmail = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2f5c5d466f5757575757575757575701404142464c5d405c40495b014c4042" rel="noreferrer noopener nofollow">[email protected]</a>"  
    email_msg = {'Message': {'Subject': "Meet for lunch?",
                            'Body': {'ContentType': 'Text', 'Content': "The new cafeteria is open."},
                            'ToRecipients': [{'EmailAddress': {'Address': toUserEmail}}]
                            },
                'SaveToSentItems': 'true'}
    
    r = requests.post(endpoint,headers={'Authorization': 'Bearer ' + result['access_token']},json=email_msg)
    if r.ok:
        print('Sent email successfully')
    else:
        print(r.json())

回应:

enter image description here

为了确认这一点,我检查了Sent Items 电子邮件发送成功,如下所示:

enter image description here

引用: python - Microsoft Graph API's "Access is denied. Check credentials and try again" - Stack Overflow by me

关于Python 使用 Graph API 和 Office365-REST-Python-Client 发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76805337/

相关文章:

python - 何时提交数据库连接?

python - 根据元组列表中的第二个元素查找具有前 5 个唯一值的所有项目

c# - 类型或命名空间名称 'AspNetCore' 在命名空间 'Microsoft' 中不存在

azure - Graph Api 响应中的 nextLink 不是绝对 Uri

Android、Microsoft Graph API - 网络无法访问

Python "private"函数编码约定

python - 我尝试从 picamera 获取 2 帧。为什么它的工作速度很慢?

c# - 多语言网站 : Azure deployment different behavior than localhost

azure - 是否可以从 Azure Function 停止/启动 Azure ARM 虚拟机?

azure-active-directory - 延迟更改带有证书的 Microsoft Graph 的 Azure AD 权限?