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

问题描述 投票:0回答:1

HI,这是用于Office 365集成的Microsoft Graph API的所有新东西。我已经查看了https://github.com/O365/python-o365处的官方文档,并且能够使用控制台程序实现邮件发送和邮件阅读代码是belwo

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!')

这里要求URL复制并粘贴完成,然后我可以

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应用程序的身份验证界面来做smae时:

我的代码

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('[email protected]')
   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

请帮助!还添加天蓝色我的应用程序权限

enter image description here

python azure-ad-graph-api office365api djnago
1个回答
0
投票

您需要设置消息的资源。

account = Account(credentials, auth_flow_type='credentials', tenant_id=tenant_id)
m = account.mailbox(resource='{the email address of sender}')
© www.soinside.com 2019 - 2024. All rights reserved.