python - 如何使用基于 Web 应用程序的身份验证在 Python Django 中使用 Microsoft graph api (python-o365) 发送和读取邮件?

标签 python django azure-ad-graph-api office365api

我不熟悉使用 Microsoft Graph API 进行 Office 365 集成。我已经阅读了 https://github.com/O365/python-o365 的官方文档,并且能够使用控制台内容实现邮件发送和邮件读取。

代码如下:

from O365 import Account

credentials = ('5ed870b6-efee-41bb-83cf-1234567890', '6a~4o-F_2~z__n97iaNAG7f7r_1234567890')
account = Account(credentials)
if account.authenticate(scopes=['basic', 'message_all']):
   print('Authenticated!')

在这里它要求复制和粘贴完成,然后我可以

def readMail(convId, account):
    mailbox = account.mailbox()
    test_mailbox = mailbox.get_folder(folder_name="Inbox")
    query = mailbox.new_query().on_attribute('conversation_id').equals(convId)
    listOfMails = []
    for message in test_mailbox.get_messages(limit=100, query=query, batch=20):
        mail_time = message.received
        # print(mail_time)
        mail_ID = message.internet_message_id
        mail_sender = message.sender
        mail_cc = message.cc
        mail_subject = message.subject
        mail_content = message.get_body_text()
        mail_dict = {'mail_time': mail_time, 'mail_ID': mail_ID, 'mail_sender': mail_sender, 'mail_cc': mail_cc,
                     'mail_subject': mail_subject, 'mail_content': mail_content}
        listOfMails.append(mail_dict)
    lastMail = listOfMails[len(listOfMails) - 1]
    # print(len(listOfMails))
    return lastMail

convId = 'AAQkAGFiYTcwOWM1LTgwNWQtNDk0Ny1hY2I0LWRjNTM2NTVjMmFhMgAQAO_HWbiF8xtLtpSPxMKOGtA='
lastMail = readMail(convId, account)

print(lastMail)


def sendMail(lastMail, account):
    mail_id = lastMail.get('mail_ID')
    mailbox = account.mailbox()
    test_mailbox = mailbox.get_folder(folder_name="Inbox")
    query = mailbox.new_query().on_attribute('internet_message_id').contains(mail_id)  # see Query object in Utils
    for message in test_mailbox.get_messages(1, query=query):
        # print("dsdsdf")
        print(message.get_body_text())
        message.mark_as_read()
        reply_msg = message.reply()
        reply_msg.body = 'Sorry Its just a Test Mail !'
        reply_msg.attachments.add('C:/Users/geetanjali.sharma/Pictures/Screenshots/Sabbatical_Fail/Screenshot (16).png')
        reply_msg.send()

sendMail(lastMail, account)

但是当我尝试使用基于 Web 应用程序的身份验证界面做同样的事情时。

我的代码:

from O365 import Account,FileSystemTokenBackend
import os
credentials = ('7c00f426-2ac5-486f-a137-1234567890', 'cOtN3a4_e.dv0WNF0.qN.xx5wgF42Tu.10.')

token_backend = FileSystemTokenBackend(token_path=os.getcwd()+'/token_folder/', token_filename='my_token.txt')
account = Account(credentials, auth_flow_type='credentials', tenant_id='3d4f5678b727a530-a0d5-4fb8-bd40-d8f9763e97db',token_backend=token_backend)
if account.authenticate():
   print('Authenticated!')
   m = account.new_message()
   m.to.add('someone@someone.com')
   m.subject = 'Testing!'
   m.body = "George Best quote: I've stopped drinking, but only while I'm asleep."
   m.send()

我得到错误

Authenticated!
Client Error: 400 Client Error: Bad Request for url: https://graph.microsoft.com/v1.0/sendMail | Error Message: Resource not found for the segment 'sendMail'.
Traceback (most recent call last):
  File "/home/ntl/Documents/projects/dataIngestionApp/dataingestionBackend/dataIngestionML/send_mail.py", line 13, in <module>
    m.send()
  File "/home/ntl/anaconda3/envs/dataai/lib/python3.7/site-packages/O365/message.py", line 694, in send
    response = self.con.post(url, data=data)
  File "/home/ntl/anaconda3/envs/dataai/lib/python3.7/site-packages/O365/connection.py", line 811, in post
    return self.oauth_request(url, 'post', data=data, **kwargs)
  File "/home/ntl/anaconda3/envs/dataai/lib/python3.7/site-packages/O365/connection.py", line 789, in oauth_request
    return self._internal_request(self.session, url, method, **kwargs)
  File "/home/ntl/anaconda3/envs/dataai/lib/python3.7/site-packages/O365/connection.py", line 751, in _internal_request
    raise HTTPError('{} | Error Message: {}'.format(e.args[0], error_message), response=response) from None
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://graph.microsoft.com/v1.0/sendMail | Error Message: Resource not found for the segment 'sendMail'.

Process finished with exit code 1

还在 Azure 中添加我的应用权限

enter image description here

最佳答案

您需要为消息设置资源。

account = Account(credentials, auth_flow_type='credentials', tenant_id=tenant_id)
m = account.mailbox(resource='{the email address of sender}')

关于python - 如何使用基于 Web 应用程序的身份验证在 Python Django 中使用 Microsoft graph api (python-o365) 发送和读取邮件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62320602/

相关文章:

Python-无线 Controller 和加数/值列表

python - 即使使用 --insecure 后 Django 图像也不会加载

Python 异常处理和引发

python - Django调试工具栏1.8离线模式

python - 搜索-根据关键字最左端的接近程度来计算相关性?

Django - 无法从 TypedChoiceField 中删除 empty_label

c# - 还原已删除的目录 Azure Active Directory 对象 - Azure Graph API

Azure AD token 颁发端点不返回 "scope"参数

python - Spyder 未启动

azure - Graph API - 自动获取电子邮件(委派权限)