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

mcdcgff0  于 2023-08-02  发布在  Python
关注(0)|答案(3)|浏览(141)

我正在尝试使用Graph API和Python发送电子邮件。我试着用graph explorer来做,它很有效。我发现了这个例子: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=["fannyd@contoso.onmicrosoft.com"]
).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=['elon.musk@company.com']
).execute_query()


即使它完全一样,在例子中,我仍然得到:

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


你能帮我解决这个问题或提供一个不同的方式发送电子邮件?

fhg3lkii

fhg3lkii1#

您正在使用客户端ID和secret,在这种情况下,您无法调用client.me.send_mail

me只有登录用户才能调用。

试着用

client.users[<mail>].send_mail(
    subject="Meet for lunch?",
    body="The new cafeteria is open.",
    to_recipients=['elon.musk@company.com']
).execute_query()

字符串

k0pti3hp

k0pti3hp2#

使用Office365 REST Python客户端安全吗?扫描Office365-REST-Python-Client python包以查找已知漏洞和缺少的许可证时未发现任何问题。因此,认为捆绑包受到保护,可以使用。

tcbh2hod

tcbh2hod3#

我同意 @user2250152 的观点,您需要将/me端点更改为client.users[<mail>].send_mail,因为您正在使用客户端凭据流来获取令牌。
我注册了一个Azure AD应用,并授予了Application类型的**Mail.Send权限:
x1c 0d1x的数据
在我的例子中,我使用下面的
修改代码**使用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 = "sri@xxxxxxxxxx.onmicrosoft.com"  
    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())

字符串

回复:



为了确认,我检查了**Sent Items**邮件发送成功的地方,如下所示:


参考:python - Microsoft Graph API的“Access is denied. Check credentials and try again”- Stack Overflow作者me

相关问题