Contact form with SendGrid

I have a database of users, that I want to have be able to submit contact forms. Depending on the customer, the email that their contact messages would go to is different, and that is in the database. I didn’t see a way to connect a Wix contact form to my database; so I created a form, which onclicking a button would call SendGrid and pass the appropriate email as the recipient.

I’ve never used SendGrid before; so perhaps I set it up wrong. It gave me a choice of Web API or SMTP Relay . I chose SMTP Relay because none of the language APIs seemed appropriate. I created my API-Key and wrote the following code, but it doesn’t send anything…

On my page I followed the various articles and posts about using SendGrid to send an email upon submission of a form.

On the back end:

//email.jsw

import {sendWithService} from 'backend/sendGrid';

export function sendEmailWithRecipient(subject, body, recipient) {
  const key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  const sender = "from.email@domain.com";
  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());
}

My form has four input fields (name, email, subject, and message) and a button.

This is the code on my page:

import wixData from 'wix-data'; // Used to query database
import wixUsers from 'wix-users'; // Used to get the current user

let msgEmail; // email of recipient

// This page is set as members only; so we just need to find out which member this is...
$w.onReady(function () {
	// Grab the current user's ID
	let user = wixUsers.currentUser;
	let userId = user.id; 
	
	// Get this user's name and email, and put it in the appropriate input fields
        // Get the email to send to (recipient) from database
wixData.query("Test")
    .eq('_id', userId)
    .find()
    .then( (results) => {
      $w('#input1').value = results.items[0].userName;
   	  $w('#input2').value = results.items[0].email;
   	  msgEmail = results.items[0].sendEmail;
   }
      
);});
import {sendEmail, sendEmailWithRecipient} from 'backend/email';
/*
$w.onReady(function () {
  $w("#sportDataset").onAfterSave(sendFormData);
});
*/
export function button1_click() {
	sendFormData; 
}

function sendFormData() {
  const subject = `New Submission from ${$w("#input3").value}`;
  const body = `Name: ${$w("#input1").value}
    \rEmail: ${$w("#input2").value}
    \rComments: ${$w("#textBox1").value}`;
  const recipient = msgEmail;
 
  sendEmailWithRecipient(subject, body, recipient)
    .then(response => console.log(response)); 
}

I’m thinking I am doing something fundamentally wrong, or it is just getting late… Any thoughts?

OK. I fixed a few things that were wrong and changed my back end function to handle a sender address as well as a recipient address being passed (sendgrid.js remained the same). I’m still not getting any emai l going through. I even generated a new API-Key at SendGrid, but that didn’t help either.

Back end:

//email.jsw
export function sendEmailWithRecipientAndSender(subject, body, recipient, sender) {
  const key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  return sendWithService(key, sender, recipient, subject, body);
}

On the page:

// libraries that we need
import wixData from 'wix-data'; // Used to query database
import wixUsers from 'wix-users'; // Used to get the current user
import {sendEmailWithRecipientAndSender} from 'backend/email';

// ...Left out function here that fills read only fields...

// Check that they don't have empty subject and message and send
export function button1_click() {
	if (($w('#input3').value !== "") && ($w('#textBox1').value !== "")){
		sendMsgData; 
		$w('#input3').value = "";
		$w('#textBox1').value = "Message Sent";
	}
	else{
		$w('#input3').value = "Subject Required!";
		$w('#textBox1').value = "Message Required!";
	}
	
}

function sendMsgData() {
     let user = wixUsers.currentUser;
     let userId = user.id;
     wixData.query("Test")
    .eq('_id', userId)
    .find()
    .then( (results) => {
          const sender = results.items[0].email;
   	  const recipient = results.items[0].sendEmail;
   	  const subject = `New Mesage from ${$w("#input3").value}`;
   	  const body = `Name: ${$w("#input1").value}
    	\rEmail: ${$w("#input2").value}
    	\rMessage: ${$w("#textBox1").value}`;    	
    sendEmailWithRecipientAndSender(subject, body, recipient, sender)
    .then(response => console.log(response)); 
 });
}

I tested to make sure that I indeed had values in the parameters that I was passing. I did, and they look valid. Is there something inherently wrong in how I am “calling” SendGrid?

Well, I’ve solved it. Yes, there was a problem with SendGrid. You need to make sure your API Key as full permissions, otherwise “post” won’t work. The majority of my problem really seemed to be in my page code, though. This finally works:

$w.onReady(function () {
	// Grab the current user's ID
	let user = wixUsers.currentUser;
	let userId = user.id; 
	
	// Get this user's name and email, and put it in the appropriate inputs
	wixData.query("OurTest")
    .eq('_id', userId)
    .find()
    .then( (results) => {
      $w('#input1').value = results.items[0].userName;
   	  $w('#input2').value = results.items[0].email;
   }
      
);}); 

$w.onReady(function () {
	$w('#button1').onClick(sendMsg);
});

function sendMsg() {
	
	let user = wixUsers.currentUser;
	let userId = user.id;
	
	wixData.query("OurTest")
    .eq('_id', userId)
    .find()
    .then( (results) => {
      const sender = results.items[0].email;
   	  const recipient = results.items[0].sendEmail;
   	  const subject = `New Mesage from ${$w("#input1").value}`;
   	  const body = `Name: ${$w("#input1").value}
    	\rEmail: ${$w("#input2").value}
    	\rSubject: ${$w("#input3").value}
    	\rMessage: ${$w("#textBox1").value}`;
    	
    	debugger;
    	
   	if (($w('#input3').value === "") || ($w('#textBox1').value === "")){
		$w('#input3').value = "Subject Required!";
		$w('#textBox1').value = "Message Required!";
	}
	else{ 	
		
    	console.log(body);
    	console.log (recipient);
    	console.log(sender);
    	sendEmail(subject, body)
    	.then(response => console.log(response)); 
    	$w('#input3').value = "";
		$w('#textBox1').value = "Message Sent";
	}
 });

This was just testing with static addresses on the backend, but I’m eventually going to change this to grab the recipient out of the database and possibly send to a second recipient as well (this works: https://www.wix.com/code/home/forum/questions-answers/wix-code-form-email-notifications).

–Al

Hello. I am having real trouble as well I cannot get this feature to work. Can someone help. Thanks.