Update: We are trying to improve the setup in Symfony to make most of this gist hopefully not needed anymore (except the token provider): symfony/symfony#52585
I banged my head against this for a while, but finally got it to work.
What you need to set this up:
- the user name (= email address) of your email account
- tenant id for your email account (a uuid)
- client id for your email account (a uuid)
- a secret token for oauth (for me that was 40 characters long)
I then set up the following services (let me know if there is a more elegant way of setting this up with symfony mailer - i did not see how else i can dynamically do the oauth2 login to get a fresh token)
services:
App\Infrastructure\Email\Office365OAuthTokenProvider:
$tenant: '%env(resolve:EMAIL_TENANT)%'
$clientId: '%env(resolve:EMAIL_CLIENT_ID)%'
$clientSecret: '%env(resolve:EMAIL_CLIENT_SECRET)%'
App\Infrastructure\Email\OAuthEsmtpTransportFactoryDecorator:
decorates: mailer.transport_factory.smtp
arguments:
$inner: '@.inner'
$authenticator: '@App\Infrastructure\Email\XOAuth2Authenticator'
and in .env set up the variables:
### symfony/mailer ###
# Username is the full email address. Need to urlencode the "@" in the username.
MAILER_DSN=smtp://email%40domain.com:@smtp.office365.com:587
###< symfony/mailer ###
EMAIL_TENANT=cafebabe-cafe-babe-cafe-babecafebabe
EMAIL_CLIENT_ID=cafebabe-cafe-babe-cafe-babecafebabe
EMAIL_CLIENT_SECRET=
And at runtime inject the right secret token.
When I add some debug, I found in logs :
[2023-11-15T11:00:17.013157+01:00] mailer.DEBUG: Email transport "Symfony\Component\Mailer\Transport\Smtp\SmtpTransport" starting [] []
[2023-11-15T11:00:17.197746+01:00] cache.INFO: Lock acquired, now computing item "email-token" {"key":"email-token"} []
[2023-11-15T11:00:17.198456+01:00] http_client.INFO: Request: "POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token" [] []
[2023-11-15T11:00:17.483973+01:00] http_client.INFO: Response: "200 https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token" [] []
[2023-11-15T11:00:17.484609+01:00] app.INFO: Token fetched successfully: {token} [] []
[2023-11-15T11:00:23.894482+01:00] app.ERROR: Error during XOAUTH2 authentication: Expected response code "235" but got code "535", with message "535 5.7.3 Authentication unsuccessful [PAZP264CA0065.FRAP264.PROD.OUTLOOK.COM 2023-11-15T10:00:23.749Z 08DBE561A3079421]". [] []
Its so strange ! The token is correctly received but the authentication fails =(
Oh my acces_token is excessively long : CHARACTERS 1479 WORDS 1 SENTENCES 3 PARAGRAPHS 1 SPACES 0