How to using Ruby Mail gem to retrieve email using POP3 and oauth2 token for office 365?

201 Views Asked by At

Currently we are using the mail gem to access our email in outlook.

Mail.defaults do
  retriever_method :pop3,
    address: "outlook.office365.com",
    port: 995,
    user_name: username,
    password: password,
    enable_ssl: true'
end

all_mails = Mail.all

According to Microsoft, they no longer support login with user_name and password for POP3 mail anymore, and now require an oauth_token from oauth2. I am able to get the token fine, but not sure if there is away to use that token in the mail gem.

1

There are 1 best solutions below

0
Stan Coder On

You could try setting it up this way

auth_url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token'
auth_params = {
  grant_type: 'refresh_token',
  refresh_token: refresh_token,
  client_id: client_id,
  client_secret: client_secret,
  scope: 'https://outlook.office365.com/POP.AccessAsUser.All'
}

auth_response = Net::HTTP.post_form(URI(auth_url), auth_params)
auth_data = JSON.parse(auth_response.body)