How do I search emails sent from the authorized account with the Office365 API v2?

67 views Asked by At

I'm using faraday and have a setup for grabbing messages from the authorized account. I have no trouble grabbing incoming messages, but when I go to grab sent messages I get an empty response when I know that the account has sent messages.

Basically, what I need is to retrieve a list emails that the user has sent.

Here's what I'm doing:

from_conn = Faraday.new(:url => "https://outlook.office.com") do |faraday|
    faraday.response :logger
    faraday.adapter Faraday.default_adapter
  end

# Then from:
from_response = from_conn.get do |request|
  request.url "/api/v2.0/Me/Messages?$search=%22from:#{user_email}%22&$select=SentDateTime,ToRecipients,From,Subject,Body"
  request.headers['Authorization'] = "Bearer #{token['token']}"
  request.headers['Accept'] = 'application/json'
  request.headers['X-AnchorMailbox'] = user_email
end

And here is the parsed response body:

[
  [0] {
    "@odata.context" => "https://outlook.office.com/api/v2.0/$metadata#Me/Messages(SentDateTime,ToRecipients,From,Subject,Body)",
             "value" => []
  }
]

It's generating a request URI of https://outlook.office.com/api/v2.0/Me/Messages?%24search=%22from%3Adr_dickdorkins%40outlook.com%22&%24select=SentDateTime%2CToRecipients%2CFrom%2CSubject%2CBody.

I've tried searching in the SentItems folder like so:

request.url "/api/v2.0/Me/Folders/SentItems$search=%22sender:#{user_email}%22"

But any permutation that I thought of to search folders yields this error:

[0] {
    "error" => {
           "code" => "RequestBroker-ParseUri",
        "message" => "Resource not found for the segment 'Folders'."
    }
}

I'm not really sure what else to try--any help is appreciated!

1

There are 1 answers

2
mlabarca On BEST ANSWER

From the docs, that doesn't look like the proper URL format to specify the folder in your last attempt. Excerpt from https://msdn.microsoft.com/en-us/office/office365/api/mail-rest-operations#get-a-message-collection-rest :

GET https://outlook.office.com/api/v2.0/me/MailFolders/{folder_id}/messages

folder_id - string - The folder ID, or the Inbox, Drafts, SentItems, or DeletedItems well-known folder name, if you're getting messages from a specific folder. Specifying AllItems would return all messages from the entire mailbox

You should try changing this url to:

https://outlook.office.com/api/v2.0/me/MailFolders/SentItems/messages/?$select=SentDateTime,ToRecipients,From,Subject,Body 

(It looks as if it's expecting MailFolders resource name instead of Folders) Also, before ruling it out a problem with the request built by faraday , you should check what the api is returning with something like advanced rest client, curl or some other REST client that lets you set the headers, then bring those settings to the rails side of things.