Search code examples
node.jsemailsendgrid

How to add a good email in sendgrid api in nodejs


I'm sending some emails via sendgrid and nodejs. I have a content to sent, but i'm unable to add a good body like below

Body:

Hi

You are receiving this email as a reminder to enter time for the day.

Best Regards, Operations Team

I'm able to send mail with the message only and couldn't find a way to add the "Best Regards, Operations Team" lines. Please give an insight.

my code,

  sgmail.setApiKey(process.env.API_KEY);
      const msg = {
        to: '########', // Change to your recipient
        from: "######", // Change to your verified sender
        subject: `Reminder for Time Entry`,
        text: "Hi You are recieving this email as a reminder to enter time for the day.",
        html: "<h1> Hi You are recieving this email as a reminder to enter time for the day.</h1>",
    }
    sgmail.send(msg);

Solution

  • In plain text you can add line breaks and they will display in the email. Note that you can use backticks (`) to write multiline strings in JavaScript. For HTML emails, you should wrap different lines in different paragraph (<p>) tags. Try the following:

    sgmail.setApiKey(process.env.API_KEY);
    
    const textMessage = `Hi
    
    You are receiving this email as a reminder to enter time for the day.
    
    Best Regards, Operations Team`;
    
    const htmlMessages = `<p>Hi</p>
    
    <p>You are receiving this email as a reminder to enter time for the day.</p>
    
    <p>Best Regards, Operations Team</p>`;
    
    const msg = {
        to: '########', // Change to your recipient
        from: "######", // Change to your verified sender
        subject: `Reminder for Time Entry`,
        text: textMessage,
        html: htmlMessage,
    }
    sgmail.send(msg);