There is a very nice writeup on this subject at https://support.wix.com/en/article/corvid-tutorial-sending-an-email-on-form-submission . It describes exactly what I need to do: allow anyone to submit an email created from form entries, sending it to me and a copy to the submitter using the sendGrid email delivery service. However, the backend module email.jsw as described shows hard coded sender and recipient email addresses. The recipient will always be me, but the sender email address must be retrieved from the database created by the form. I need to know how to make the dataset available to the backend code, or some other magic to supply the sender email address.
//email.jsw
import {sendWithService} from ‘backend/sendGrid’;
export function sendEmail (subject, body) {
const key = “QL.cFH5YHZQQ2_fG0z_KuQ.6WPTYEyjN1C3_7Wt9Hb3jGfkJNAyzJhz3ddhM”;
const sender = “from.email@domain.com”;
const recipient = “to.email@domain.com”;
return sendWithService(key, sender, recipient, subject, body);
}
Thanks very much in advance.
I I forgot to mention that it works fine with a hard-coded sender address.
I think that you are getting yourself confused with how the tutorial works.
You do need to add your own email in the email.jsw backend file, so both the const sender and the const recipient will be your own email address.
It does not matter if you used both the sendEmail and the sendEmailWithRecipient functions either, both of them need the const sender and const recipient lines to be filled in with your own email address.
The part where it gets the actual email for the user is from the page code as stated in the tutorial where the code gets the email address and any other input values that you added to this section…
We also need to modify the front-end code so that it imports the new function and uses it to send the email, specifying who the recipient is.
import {sendEmail, sendEmailWithRecipient} from 'backend/email';
$w.onReady(function () {
$w("#sportDataset").onAfterSave(sendFormData);
});
function sendFormData() {
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 recipient = $w("#emailInput").value;
sendEmailWithRecipient(subject, body, recipient)
.then(response => console.log(response));
}
After the user submits the form the code will run and send the form, hence why you use the Wix Dataset API and the onAfterSave hook in the onReady page code.
See here for more info about it.
onAfterSave( )
Adds an event handler that runs just after a save.
Description
The onAfterSave() function allows you to optionally perform actions right after a save() operation. When you call save(), the callback is run after the save has successfully completed.
Calling onAfterSave() on a read-only dataset causes an error.