Question:
I have seen an article from WIX that says we can add HTML to our email template AND parse a dynamic variable there as well.
I managed to get it working with an email signature (that I coded in html), but not the following:
Here is a screenshot of the email:
Here is a screenshot of the variable in the html component (maybe I need to nest the variable inside of some html code).
Here is a snippet from my frontend and backend code:
Frontend:
$w("#sendEmailButton").onClick(() => {
const isEmailEnabled = $w("#emailToggle").checked;
if (!isEmailEnabled) {
console.log("Email sending is disabled by the toggle.");
return;
}
try {
const email = $w("#emailAddress").value;
if ($w("#emailAddress").valid) {
// Retrieve the preview content from the rich text input field
const previewContent = $w("#emailPreviewContent").value;
$w("#sendEmailButton").disable();
$w("#sendEmailButton").label = "Sending...";
sendCustomerVisitEmail(email, previewContent)
.then(() => {
$w("#sendEmailButton").enable();
$w("#sendEmailButton").label = "Send Email";
wixWindow.openLightbox("emailSuccess");
})
.catch((error) => {
console.error("Error sending customer visit email:", error);
$w("#sendEmailButton").enable();
$w("#sendEmailButton").label = "Send Email";
wixWindow.openLightbox("emailError");
});
} else {
console.error("Email validation failed");
}
} catch (error) {
console.error("Error preparing email sending:", error);
}
});
$w("#generateEmailPreview").onClick(() => {
// Reintroduce the missing function in the current scope
function formatLabelForUrl(label) {
return label.toLowerCase().replace(/ /g, "-").replace(/[^\w-]+/g, "");
}
try {
const customerName = $w("#customerName").value;
const personalMessage = $w("#personalMessage").value;
const repDropdownValue = $w("#repDropdown").value || "";
const repDropdownLabel = $w("#repDropdown").options.find(option => option.value === repDropdownValue)?.label || "";
const productArrayLinks = JSON.parse(local.getItem("selectedProducts") || "[]").map(product => ({
url: `https://www.cwbrands.com.au/product/${product.title}`,
label: `${product.title} ${product.description}`
}));
const rangeArrayLinks = JSON.parse(local.getItem("selectedRanges") || "[]").map(rangeTitle => ({
url: `https://www.cwbrands.com.au/range/${formatLabelForUrl(rangeTitle)}`,
label: rangeTitle
}));
wixData.query("affiliateID")
.eq("title", repDropdownLabel)
.limit(1)
.find()
.then((results) => {
if (results.items.length > 0) {
const repDetails = results.items[0];
const repName = repDetails.name || "";
const repJobTitle = repDetails.repJobTitle || "";
const repEmailAddress = repDetails.repEmailAddress || "";
const repPhoneNumber = repDetails.repPhoneNumber || "";
let emailBody = "";
if (productArrayLinks.length > 0 || rangeArrayLinks.length > 0) {
emailBody += `<p>Here are some of the products we spoke about today:</p>`;
if (productArrayLinks.length > 0) {
emailBody += `<p><strong>Products:</strong><br>${productArrayLinks.map(link => `<a href="${link.url}" target="_blank">${link.label}</a>`).join("<br>")}</p>`;
}
if (rangeArrayLinks.length > 0) {
emailBody += `<p><strong>Ranges:</strong><br>${rangeArrayLinks.map(link => `<a href="${link.url}" target="_blank">${link.label}</a>`).join("<br>")}</p>`;
}
}
const previewContent = `
<div style="font-family: Arial, sans-serif; font-size: 14px; line-height: 1.5;">
<p>Hi ${customerName},</p>
<p>Thank you for taking the time to meet with me today. I appreciate the opportunity to discuss your needs and how we can assist you.</p>
<p>Here are some of the products we spoke about today:</p>
<p><b>Products:</b><br>
${productArrayLinks
.map(
(link) =>
`<a href="${link.url}" style="color: #0078d4; text-decoration: none;" target="_blank">${link.label}</a>`
)
.join("<br>")}
</p>
<p><b>Ranges:</b><br>
${rangeArrayLinks
.map(
(link) =>
`<a href="${link.url}" style="color: #0078d4; text-decoration: none;" target="_blank">${link.label}</a>`
)
.join("<br>")}
</p>
<p>If you have any further questions or require additional information, please don’t hesitate to reach out.</p>
<p>${personalMessage}</p>
<p>Kind Regards,</p>
<p>---</p>
<p>${repName}<br>${repJobTitle}<br>
<a href="mailto:${repEmailAddress}" style="color: #0078d4; text-decoration: none;">${repEmailAddress}</a><br>${repPhoneNumber}
</p>
</div>
`;
console.log("Generated Email Preview:\n", previewContent);
// Update the rich text input field with formatted HTML
$w("#emailPreviewContent").value = previewContent; // Populate as HTML
} else {
console.error('No affiliate ID found for selected rep');
}
})
.catch((error) => {
console.error("Error querying affiliate ID:", error);
});
} catch (error) {
console.error("Error generating email preview:", error);
}
});
Backend:
export function sendCustomerVisitEmail(email, previewContent) {
const contactInfo = {
name: {
first: "Customer",
last: "Visit"
},
emails: [{ email }],
};
const options = {
allowDuplicates: true,
suppressAuth: true
};
return contacts.createContact(contactInfo, options)
.then((resolvedContact) => {
console.log(`Contact created successfully with ID: ${resolvedContact._id}`);
return sendEmailToContact(resolvedContact._id, previewContent);
})
.catch((error) => {
if (error.name === 'ContactAlreadyExists') {
console.warn(`Contact already exists for email: ${email}`);
return contacts.queryContacts()
.eq("info.emails.email", email)
.find({ suppressAuth: true })
.then((queryResult) => {
if (queryResult.items.length > 0) {
const existingContactId = queryResult.items[0]._id;
console.log(`Existing contact found with ID: ${existingContactId}`);
return sendEmailToContact(existingContactId, previewContent);
} else {
console.error('Error: Contact exists but was not found in query results');
return Promise.reject(new Error('Contact exists but was not found in query results'));
}
})
.catch((queryError) => {
console.error("Error querying existing contact:", queryError);
return Promise.reject(queryError);
});
} else {
console.error("Error creating contact:", error);
return Promise.reject(error);
}
});
}
function sendEmailToContact(contactId, previewContent) {
const emailOptions = {
variables: {
emailBody: previewContent
}
};
return triggeredEmails.emailContact('USeT3N3', contactId, emailOptions)
.then(() => {
console.log(`Email sent successfully to contact ID: ${contactId}`);
return { success: true, message: `Email sent successfully to contact ID: ${contactId}` };
})
.catch((error) => {
console.error(`Error sending email to contact ID: ${contactId}`, error);
return { success: false, message: `Error sending email to contact ID: ${contactId}`, error: error.message };
});
}
For reference, here is the article from WIX saying you can add dynamic variables.