Sending Template Emails with SendGrid V3

Hi Guys

This is a quick update from this awesome post by WiX(Velo Tutorial: Sending an Email on Form Submission | Help Center | Wix.com). It shows how to upgrade to SendGrid V3 (from V2) and how to incorporate your template.

Create 1st backend file(exactly the same as V2):
//email.jsw

import {sendInstruction} from 'backend/sendGrid';

export function sendEmail(subject, body, Recipient) {
  const key = "xxxxxxxxxxYourAPIKeyHerexxxxxxx";
  const sender = "senderEmailAddress";
  return sendInstruction(APIKey, sender, Recipient, Subject, body);
}

Create the 2nd backend file(this one is quite different to the article). Note the addition of the template_id, this is where you will add your template ID that you retrieve after having created a transactional template in your SendGrid Account. Also note all the addition of ‘personalizations’, the change in overall structure and the massive amount of extra brackets, it seems they are actually neccesary…
//sendGrid.js

import {fetch} from 'wix-fetch'; 

export function SendInstruction(APIKey, Sender, RecipientEmail, Subject, body) {
	const url = "https://api.sendgrid.com/v3/mail/send";
		
	const MyHeaders = {
		"Authorization": "Bearer " + APIKey,
		"Content-Type": "application/json"
	};
	const MyBody = {
		"personalizations": [{
			"to": [{
				"email": RecipientEmail
			}]
		}],
		"from": {
			"email": Sender
		},
		"subject": Subject,
		"content": [{
			"type": "text/html",
			"value": body
		}],
		"template_id" : "xxxxxxxxYourTemplateIDHerexxxxxx"
	};

	return fetch(url, {
			"method": "POST",
			"headers": MyHeaders,
			"body": JSON.stringify(MyBody)
		})
		.then(Response => Response.text);		
}

Lastly, create you page code. This is also exactly the same as the article

import {sendEmail} from 'backend/email';

function SendClientEmail() {
const Subject = `New Submission from ${$w("#nameInput").value}`;
const body =  `Name: ${$w("#nameInput").value}     
\rEmail: ${$w("#emailInput").value}     
\rSport: ${$w("#sportDropdown").value}     
\rComments: ${$w("#commentsInput").value}`;
const RecipientEmail = `recipientEmailHere`;

  sendEmail(Subject, body, RecipientEmail)
    .then(response => console.log(response)); 
}

That’s it… Happy coding!

5 Likes

Hello Tiaan,

Thanks for sharing the code, it’s working fine for me excepte one point.

const body variable in my code is like:

const body = Hey there, \r \rThanks for subscribing to the Daaman Welfare Trust's newsletter. We recognize that your time is valuable and we are seriously flattered that you chose to join us with your mail id ${$w("#emailInput").value}. \r \rThe Daaman newsletter endeavors to send you only the relevant content. If we ever stray from that, just send us an email at admin@daaman.org and we’ll do our best to get it straightened out. \r \rIn the meantime, we’d love to hear from you about why you’ve subscribed to our list, and what you’re interested in learning about. \r \rIf you need any assistance, please feel free to drop us an email at info@daaman.org. \r \rAgain, welcome! \r \rBest regards \rTeam Daaman;

With V2 this was working absolutely fine putting all paragraphs seperately, but with V3 code “\r” isn’t working I guess. It’s sending whole of body text as single paragraph.

Please gude how to rectify this issue.

Thanking in anticipation.
Anupam Dubey

Hi Anupam

I noticed this as well, it’s something to do with SendGrid converting text to html on their end. One of the solutions they’ve provided was to start the body part with

, this forces the paragraph to render as text. This works, but makes the text very small and almost unreadable. I’ve seen other guys using \n instead of \r, but that doesn’t seem to work either…

As an alternative, you could write your body in the template itself and just substitute the dynamic values, they have a tutorial on it somewhere if I remember correctly. This, I think is how they designed it to work.

Best of luck!
Tiaan

Hello Tiaan,

Can you please share a modified code so that Template-id is also passed through page code? That’ll solve a lot of problems for those who have more than one form/interaction to mail through sendgrid. Am novice in coding, just wondering how to go about it.

Please help

Thanking in anticipation.

Anupam Dubey

Hi Anupam

I can see the value of this. Below is the modified code. Note, I haven’t tested it, so if it works, kindly confirm that here.

Page code:

import {sendEmail} from 'backend/email'; 

function SendClientEmail() { 
const Subject = `New Submission from ${$w("#nameInput").value}`; 
const body = `Name: ${$w("#nameInput").value}      
\rEmail: ${$w("#emailInput").value}      
\rSport: ${$w("#sportDropdown").value}     
 \rComments: ${$w("#commentsInput").value}`; 
const RecipientEmail = `recipientEmailHere`; 
const TemplateID = `xxxxxxx-templateId here-xxxxxxx`;

sendEmail(Subject, body, RecipientEmail, TemplateID) 
.then(response => console.log(response)); 
}

//email.jsw

import {sendInstruction} from 'backend/sendGrid'; 

export function sendEmail(subject, body) { 
const key = "xxxxxxxxxxYourAPIKeyHerexxxxxxx"; 
const sender = "senderEmailAddress"; 
return sendInstruction(APIKey, sender, Recipient, Subject, body, TemplateID);
}

//sendGrid.js

import {fetch} from 'wix-fetch'; 

export function SendInstruction(APIKey, Sender, RecipientEmail, Subject, body, TemplateID) {
const url = "https://api.sendgrid.com/v3/mail/send"; 

const MyHeaders = { "Authorization": "Bearer " + APIKey, 
"Content-Type": "application/json" }; 

const MyBody = { "personalizations": [{ 
"to": [{"email": RecipientEmail}]}], 
"from": { "email": Sender}, 
"subject": Subject, 
"content": [{"type": "text/html", "value": body}], 
"template_id" : "TemplateID"}; 

return fetch(url, { "method": "POST", "headers": MyHeaders, "body": JSON.stringify(MyBody) 
.then(Response => Response.text); 
}

Let us know if it works!

Tiaan

Thanks Tiaan,

Will surely try this on first opportunity and let you know.

Thank for the pointer above which showed me how to implement SendGrid v3 API in principle. For anyone interested in using it to send CSV attachments created on the fly, here is the code which worked for me, where you can see the attachments object replaces the template_id body parameter which I wasn’t using:

const MyBody = { 
	"personalizations": [{ 
		"to": [{ 
			"email": RecipientEmail 
		}] 
	}], 
	"from": { 
		"email": Sender 
	}, 
	"subject": Subject, 
	"content": [{ 
		"type": "text/html", 
		"value": body 
	}], 
	"attachments": [{ 
		"content": CSVContents, 
		"filename": "test.csv" 
	}] 
}; 

It is crucial to remember that CSVContents (just my chosen name for the variable) needs to be base64 encoded which took me a while to figure out. The Javascript function is btoa(string), but it only works in front end browser based code, so you just pass the result through to this backend function through adding it as a function parameter, so my version of this backend function now looks like this:

export function SendInstruction(APIKey, Sender, RecipientEmail, Subject, body, CSVContents) {
const url = “https://api.sendgrid.com/v3/mail/send”;

etc etc…

Can you provide the coding to send also the notification email to the client through sendgrid template

Would anyone be able to show there template? I have been playing around with this and was wondering if you can link the fields from your page, to the template (so you can change the format of the text etc)

Hi everyone,

This works for me but in the const body part of the email I have:

‘Name: ${$w(" #nameInput ").value}’

But instead of showing what is actually in my #nameInput field it actually sends the email saying ${$w(" #nameInput ").value}. What could be the issue?

Hi,
My guess is you are not using backticks.

Roi.

Tried to implement this code and it doesn’t work. had the email sending when I was set to v2 throught the original walkthrough but when I tried to move to v3 and add a sendgrid template the email request never hit sendgrid. Can someone please help!

See the Example: Send email with the SendGrid NPM interface . Hopefully this will help.

@yisrael-wix thanks for the help but there are no available packages in my
package manager…

@stewart Strange - I see them fine:

@yisrael-wix


nothing for me…

@stewart Hmm… Did you recite the required mystical incantations and burn incense?

Please post the editor URL of your site so we can inspect. Only authorized Wix personnel can get access to your site in the editor.

@yisrael-wix that was the next thing I was going to try…

@stewart Seems like you should find a pack of matches…

Seems the problem might be system related - it doesn’t appear to be a code issue.

I would recommend contacting the Wix support team , as they can better assess your problem and direct it to the proper team.

understood - looks like I need to head off to them to understand how to do that!
Thanks again for your help