Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending email using office365 server with swiftmailer in symfony

I'm trying to send an confirmation email after registration using swiftmailer and office365 server in symfony. I've tried every combination of host,port and encryption type I've come across.

Currently my .env file contains this line:

MAILER_URL=smtp://smtp.office365.com:587?encryption=ssl&auth_mode=login&username="[email protected]"&password="mypassword"

*Note: I've used " " for my username and password since they contain special characters and I've read somewhere that this can cause problems with MAILER_URL.

My swiftmailer.yaml file containts this:

swiftmailer:
    url: '%env(MAILER_URL)%'
    stream-options:
        ssl:
            allow_self_signed : true
            verify_peer: false

Lastly, I'm sending my email using this code in my controller:

 $message = (new \Swift_Message('Referral tool registration'))
            ->setFrom('[email protected]')
            ->setTo('[email protected]')
            ->setBody(
                $this->renderView(
                    'email/notification/user_registered.html.twig',
                    ['firstName' => $user->getFirstName(),
                     'lastName' => $user->getLastName()
                    ]
                    ),
                'text/html'
            );

 $mailer->send($message);

With the current choice of host,port and encryption I'm getting: "Connection could not be established with host smtp.office365.com [ #0]"

UPDATE: When I type in telnet smtp.office365.com 587 I get a valid response, so I suppose the problem is not network related, port is not blocked.

like image 347
Mario Klisanic Avatar asked Jan 25 '23 20:01

Mario Klisanic


1 Answers

You have to use encryption=tls, urlencode your USER_NAME and PASSWORD, and you should not wrap USER_NAME and PASSWORd in quotes as you did.

Let's assume these credentials and urlencode them:

USERNAME = `[email protected]` → `email%40domain.tld`
PASSWORD = `pa$$w#rd` → `pa%24%24w%23rd`

Correct config with above credentials will look like this:

MAILER_URL=smtp://smtp.office365.com:587?encryption=tls&auth_mode=login&username=email%40domain.tld&password=pa%24%24w%23rd
like image 154
gondo Avatar answered Jan 28 '23 11:01

gondo