File attachment using Sendgrid

I want to send file in email and not the url of the file
how can I add concate it to body?

here is my code:

export function sendWithService ( key , sender , recipient , subject , body ) {
const url = “https://api.sendgrid.com/api/mail.send.json” ;

const  headers  = { 
    "Authorization" :  "Bearer "  +  key , 
    "Content-Type" :  "application/x-www-form-urlencoded" 
}; 

const  data  =  `from= ${ sender } &to= ${ recipient } &subject= ${ subject } &text= ${ body }`; 

const  request  = { 
    "method" :  "post" , 
    "headers" :  headers , 
    "body" :  data 
}; 

**return**  fetch ( url ,  request ) 
    . then ( response  =>  response . json ()); 

}

I suggest to install the @sendgrid/mail npm and use it to handle all your mails (it is very easy to use).

  • install the pdf-to-base64 npm.
    Then use fetch to get the file, convert it into base64 and do something like:

(I haven’t tested the code and there might be typos etc…)

import sgMail from '@sendgrid/mail';
import { getSecret } from 'wix-secrets-backend';
const getKey = () => getSecret("sendgrid-key");//use the key as you put in you Secret Manager
export async function sendEmail(data){
 const key = await getKey();
 const pdf2base64 = require('pdf-to-base64');
const attachment = await pdf2base64(data.fileUrl);
   sgMail.setApiKey(key);
const msg = {
        to: data.senderEmail,
        from: data.recipientEmail,
        templateId: "d-34349fa143454dsd2356161cd3862a",//the template ID as appears on your Sendgrid dashboard
        dynamic_template_data: {
                subject: data.subject,
		name: data.name//any dynamic data that you use in your template
        }
    };
    if(attachment){
    msg.attachments = [
    {
      content: attachment,
      filename: "attachment.pdf",
      type: "application/pdf",
      disposition: "attachment"
    }
  ]
    }
    return sgMail.send(msg);
}


UPDATED

Interesting…:grin: