WIX and SendGrid integration in form not working

Hi! I’m trying to get my submission form in WIX to work with SendGrid but I haven’t figured out how. Basically, when someone submits a form, I need to send 2 emails; one for me, one for the user. This is the code I’ve done for now.

//email.jsw

import {sendWithService} from ‘backend/sendGrid’;

export function sendEmail(subject, body) {
const key = “SG.KEY”;
const sender = “myemail”;
const recipient = “myemail”;
return sendWithService(key, sender, recipient, subject, body);
}

export function sendEmailWithRecipient(subject, body, recipient) {
const key = “SG.KEY”;
const sender = “myemail”;
return sendWithService(key, sender, recipient, subject, body);
}


//sendGrid.js

import {fetch} from ‘wix-fetch’;

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());
}


//PageCode

import {sendEmail, sendEmailWithRecipient} from ‘backend/email’;

$w.onReady( function () {
$w(“#dataset1”).onAfterSave(sendFormData);
});

function sendFormData() {
const subject = ‘Submission successful’
const body = \rFullName: ${$w("#fullname").value} \rEmail: ${$w("#email").value} \rPhone: ${$w("#phone").value} \rNumber: ${$w("#number").value} \rLocation: ${$w("#location").value};
const recipient = $w(“#email”).value;

sendEmailWithRecipient(subject, body, recipient)
.then(response => console.log(response));

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

I’d appreciate any assistance! Thank you in advance!

Hi Owen,

You code is all fine apart from one place.

On your page code where you have this:
const body = ` \rFullName: ${$w(" #fullname ").value}

You actually need it to be like this:
const body = ` FullName: ${$w(" #fullname ").value}
You don’t need the \r in this line, only in the following lines that determine your user input elements.

I have my own setup like the following so I have the same in the header and the message, however you can change it to whatever you have already.
const subject = Join Us Form Submitted From ${$w("#firstName").value};
const body = `Join Us Form Submitted From ${$w(“#firstName”).value}
\rFirst Name: ${$w(“#firstName”).value}

Plus, (obviously), you have need to re-enter your SendGrid API key and email address in the email.jsw backend file.


please help me to figure out the problem, not able send mail in my mailbox. tried so many times but no solution found. Please suggest what should i do now.