Laravel & Sendgrid

If you want to send Laravel form data using Sendgrid use this for .env (using your own details of course):

MAIL_DRIVER=smtp
MAIL_HOST=smtp.sendgrid.net
MAIL_PORT=587
MAIL_USERNAME=apikey
MAIL_PASSWORD=very_long_key
MAIL_ENCRYPTION=tls
MAIL_FROM_NAME="Company Name"
MAIL_FROM_ADDRESS=info@domain.com

The username should be “apikey” so it can work with API Key as the password!

If you made any mistakes you will probably get an error 500 and should check the logs tail -n 63 ~/domain.com/storage/logs/your_log.log where you will see something like

[2020-01-21 02:54:47] production.ERROR: Failed to authenticate on SMTP server with username "some-name" using 2 possible authenticators. Authenticator LOGIN returned Expected response code 250 but got an empty response. Authenticator PLAIN returned Expected response code 250 but got an empty response. {"userId":1,"exception":"[object] (Swift_TransportException(code: 0): Failed to authenticate on SMTP server with username \"some-name\" using 2 possible authenticators. Authenticator LOGIN returned Expected response code 250 but got an empty response. Authenticator PLAIN returned Expected response code 250 but got an empty response. at /home/forge/domain.com/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/AuthHandler.php:191)
 [stacktrace]

And that tells you the username or password was wrong. So update and reload .env for this. Laravel Forge reloads on saving the.env file.

Account Vetting

If there are still errors it could be that your SendGrid account has not been properly vetted yet. I have had the pleasure of setting up an account twice. This due to incorrect adding of domain name on first setup.

API Access

Either that or you need full access for API key. In that case edit the key and grant it full access.

I sometimes forget to to that.

Bonus: API Key Test

Then do a quick curl test to see if the api key works do:

➜  ~ curl -X "GET" "https://api.sendgrid.com/v3/templates" -H "Authorization: Bearer very_long_api_key_given_to_you" -H "Content-Type: application/json"
 {"templates":[]}

If you needed full access before the answer would have been:

{"errors":[{"field":null,"message":"authorization required"}]}%

The key needs to work well otherwise it cannot be used.. duh.

Jasper Frumau

Jasper has been working with web frameworks and applications such as Laravel, Magento and his favorite CMS WordPress including Roots Trellis and Sage for more than a decade. He helps customers with web design and online marketing. Services provided are web design, ecommerce, SEO, content marketing. When Jasper is not coding, marketing a website, reading about the web or dreaming the internet of things he plays with his son, travels or run a few blocks.