我正在尝试使用 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=["[email protected]"]
).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=['[email protected]']
).execute_query()
尽管它与示例中的一模一样,但我仍然得到:
TypeError: send_mail() got an unexpected keyword argument 'subject'
您可以帮我解决此问题或提供其他发送电子邮件的方式吗?
您正在使用客户端 ID 和密码,在这种情况下您无法致电
client.me.send_mail
。
仅当您以用户身份登录时才能调用me。
尝试使用
client.users[<mail>].send_mail(
subject="Meet for lunch?",
body="The new cafeteria is open.",
to_recipients=['[email protected]']
).execute_query()
使用Office365 REST Python客户端安全吗?扫描 Office365-REST-Python-Client python 包是否存在已知漏洞和缺少许可证时,未发现任何问题。因此,该捆绑包被认为是受保护的,可以使用。
我同意@user2250152,您需要将
端点更改为/me
,因为您正在使用客户端凭证流程来获取令牌。client.users[<mail>].send_mail
我注册了一个 Azure AD 应用程序并授予了
Mail.Send
Application 类型的权限:
在我的例子中,我使用下面的修改后的代码使用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 = "[email protected]"
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
,电子邮件已成功发送,如下所示: