Send emails using Sendgrid with google appscript

前端 未结 3 831
别那么骄傲
别那么骄傲 2021-02-06 18:26

I am creating a googlesheet addon to send mails.And for sending mails I am using sendgrid. I cannot find any documentation or example code for sending mails with Google Appscrip

3条回答
  •  既然无缘
    2021-02-06 18:40

    For anyone who has this issue in the future with Transactional Email Template:

    https://sendgrid.com/docs/ui/sending-email/how-to-send-an-email-with-dynamic-transactional-templates/

    This is the function to send (similar to the answer of Nikil Mathew, but for transactional email template with dynamic data):

    export const sendBySendGrid = (toEmail, templateId, dynamicTemplateData) => {
      const headers = {
        Authorization: `Bearer ${process.env.SENDGRID_API_KEY}`,
        'Content-Type': 'application/json',
      }
    
      const body = {
        from: {
          email: process.env.SENDGRID_FROM_EMAIL,
          name: process.env.SENDGRID_FROM_NAME,
        },
        personalizations: [
          {
            to: [
              {
                email: toEmail,
              },
            ],
            dynamic_template_data: dynamicTemplateData,
          },
        ],
        template_id: templateId,
      }
    
      const options = {
        method: 'POST',
        headers,
        payload: JSON.stringify(body),
      }
    
      const response = UrlFetchApp.fetch('https://api.sendgrid.com/v3/mail/send', options)
    
      Logger.log(response)
    }
    

    You can update process.env.SENDGRID_API_KEY, process.env.SENDGRID_FROM_EMAIL, process.env.SENDGRID_FROM_NAME with your SendGrid credentials

提交回复
热议问题