I see plenty of answers around the internet, including the Wix community forum:
https://forum.wixstudio.com/t/file-attachment-using-sendgrid-api/34156
BUT they require a .js setup, while I already have a .jsw setup.
Do I really have to build a completely new backend? Can’t I make this work with the .jsw code I already have?
My backend:
// backend/sendEmail.jsw
import sgMail from '@sendgrid/mail';
import wixSecretsBackend from 'wix-secrets-backend';
export async function sendEmail({ to, subject, text, replyto, fromname }) {
try {
const sendGridSecret = JSON.parse(await wixSecretsBackend.getSecret('sendGridSecret'));
const key = sendGridSecret.key;
const senderEmail = sendGridSecret.senderEmail;
sgMail.setApiKey(key);
const msg = {
from: {
email: senderEmail,
name: fromname // Use the provided sender name (wix current user)
},
replyTo: replyto, // Use the provided reply-to address
to: to,
subject: subject,
text: text
};
const result = await sgMail.send(msg);
console.log('Email Result:', result);
return result;
} catch (error) {
console.error('Error sending the email:', error.response?.body || error.message);
throw error; // Rethrow the error to propagate it to the caller
}
}
.
My frontend:
(...)
if (urlId) {
const projectEmail = await getProjectEmail(urlId);
const projectTitle = await getProjectTitle(urlId);
if (projectEmail && projectTitle) {
$w('#sendButton').onClick(async () => {
const passedValidations = checkFormFields();
if (passedValidations) {
try {
displayMessage('Sender...');
const emailResult = await sendEmail({
to: projectEmail,
subject: $w('#subject').value,
text: "*** nDenne besked er sendt fra en profil på kreativthold.dk, til '" + projectTitle + "'. nOBS: Nogle vedhæfter en fil, tjek selv. nDu kan svare personen direkte, ved at svare på denne mail. n*** nn" + $w('#emailContent').value,
replyto: $w('#replyToMail').value,
fromname: $w('#fromName').value
});
if (emailResult && emailResult[0]?.statusCode === SUCCESS_CODE) {
clearFields();
displayMessage('Din mail er sendt!'); // Success message
} else {
displayMessage('Noget gik galt, kontakt support.'); //sendGrid fejl?
}
} catch (error) {
displayMessage('Kunne ikke sende mail, tjek felter.');
}
} else {
displayMessage('Fejl, tjek at alle felter er udfyldt.');
}
});
} else {
// Handle the case where the user is not found
console.error('User not found.');
}
} else {
// Handle the case where the userID is not present in the URL
console.error('UserID not found in the URL.');
}
});
(...)
Is it really not possible to add the SendGrid attachment code when my backend is a .jsw instead of a .js ?
I’m scared of messing up my code, tbh..
Lots of thanks in advance