无法使用Microsoft Graph API使用Python Django发送Outlook电子邮件

时间:2019-12-24 03:55:30

标签: python django outlook microsoft-graph

我目前正在尝试将Outlook电子邮件集成到我的Web应用程序中。我可以使用“ GET”请求从我的Outlook电子邮件中检索电子邮件,日历和联系人。但是,我无法使用“ POST”请求发送电子邮件。我不确定我要去哪里。任何帮助表示赞赏。以下是我的一些相关代码:

outlookservice.py

select c.name,
IFNULL (b.num,0) as 'num'
from
(select name from a
union 
select name from b) c
left join b
on c.`name`=b.`name`

views.py

graph_endpoint = 'https://graph.microsoft.com/v1.0{0}'

# Generic API Sending
def make_api_call(method, url, token, payload = None, parameters = None):
  # Send these headers with all API calls
  headers = { 'User-Agent' : 'python_tutorial/1.0',
              'Authorization' : 'Bearer {0}'.format(token),
              'Accept' : 'application/json' }

  # Use these headers to instrument calls. Makes it easier
  # to correlate requests and responses in case of problems
  # and is a recommended best practice.
  request_id = str(uuid.uuid4())
  instrumentation = { 'client-request-id' : request_id,
                      'return-client-request-id' : 'true' }

  headers.update(instrumentation)

  response = None

  if (method.upper() == 'GET'):
      response = requests.get(url, headers = headers, params = parameters)
  elif (method.upper() == 'DELETE'):
      response = requests.delete(url, headers = headers, params = parameters)
  elif (method.upper() == 'PATCH'):
      headers.update({ 'Content-Type' : 'application/json' })
      response = requests.patch(url, headers = headers, data = json.dumps(payload), params = parameters)
  elif (method.upper() == 'POST'):
      headers.update({ 'Content-Type' : 'application/json' })
      response = requests.post(url, headers = headers, data = json.dumps(payload), params = parameters)

  return response
  
def send_mail(access_token):
  send_mail_url = graph_endpoint.format('/me/sendMail')

  query_parameters = {
  "message": {
    "subject": "Meet for lunch?",
    "body": {
      "contentType": "Text",
      "content": "The new cafeteria is open."
    },
    "toRecipients": [
      {
        "emailAddress": {
          "address": "angyangcheng@outlook.com"
        }
      }
    ],
    "ccRecipients": [
      {
        "emailAddress": {
          "address": "angyangcheng@outlook.com"
        }
      }
    ]
  },
  "saveToSentItems": "true"
  }

  r = make_api_call('POST', send_mail_url, access_token, parameters=query_parameters)

  if (r.status_code == requests.codes.ok):
    return r.json()
  else:
    return "{0}: {1}".format(r.status_code, r.text)

send.html

def send(request):
  access_token = get_access_token(request, request.build_absolute_uri(reverse('tutorial:gettoken')))
  if not access_token:
    return HttpResponseRedirect(reverse('tutorial:home'))
  else:
    send = send_mail(access_token)
    return render(request, 'tutorial/send.html')

0 个答案:

没有答案