Home > Mobile >  SendGrid email works locally but not on Azure app service
SendGrid email works locally but not on Azure app service

Time:01-28

I'm using sendgrid in next.js to send emails. It works perfectly fine on localhost, but when I deploy it to Azure app service and try to send an email, it throws an error and the error is an empty object.

I'm building the next app locally with docker and then uploading and deploying that image onto the azure app service. This is to allow the local environment variables to be included in the build.

/api/send-mail

import type { NextApiRequest, NextApiResponse } from 'next'



// https://github.com/sendgrid/sendgrid-nodejs/tree/main/packages/mail#quick-start-hello-email
// https://docs.sendgrid.com/for-developers/sending-email/quickstart-nodejs#build-your-api-call

import sgMail from '@sendgrid/mail'

sgMail.setApiKey(process.env.SEND_GRID_API_KEY)

const handler = async (req: NextApiRequest, res: NextApiResponse) => {

    if(req.method == 'GET') {

        const msg = "This is a test message"

        sgMail.send({
            to: process.env.SERVICES_INQUIRIES_EMAIL,
            from: process.env.SEND_GRID_VERIFIED_EMAIL,
            subject: "Test Email",
            html: msg
        }).then(() => {
            return res.status(200).json({'success': true})
        }, error => {
            return res.status(500).json({'test error': error})
        })
    }

}

export default handler

When I hit this endpoint on localhost, I get {"success":true}, but when I deploy onto the app service, I get {"test error":{}}.

This shouldn't be an environment variable issue, because other env variables work on the live site. Any insight is much appreciated.

CodePudding user response:

Did you used a environment variables in Azure App Service ?

If not please do so: enter image description here

Hope this will help

  • Related