optimize normalization
This commit is contained in:
@ -58,35 +58,34 @@ function setResult(result) {
|
||||
exports.GetLastResult = function () {
|
||||
return lastResult;
|
||||
};
|
||||
|
||||
function normalizeEmailAddresses(to) {
|
||||
// If 'to' is already a string, it could be a single email or a CSV of emails
|
||||
let emails = [];
|
||||
|
||||
if (typeof to === 'string') {
|
||||
// Check if 'to' is a CSV string of emails; split it into an array if true
|
||||
if (to.includes(',')) {
|
||||
return to.split(/\s*,\s*/); // Split by comma and trim spaces around emails
|
||||
}
|
||||
// Otherwise, return it as a single-element array
|
||||
return [to];
|
||||
}
|
||||
|
||||
// If 'to' is an array, determine if it's an array of strings or objects
|
||||
if (Array.isArray(to)) {
|
||||
return to.map(item => {
|
||||
// If the item is a string, return it directly
|
||||
// Handle CSV string by splitting into an array
|
||||
if (to.includes(',')) emails = to.split(/\s*,\s*/);
|
||||
else emails = [to]; // Handle single email string
|
||||
} else if (Array.isArray(to)) {
|
||||
emails = to.map(item => {
|
||||
if (typeof item === 'string') return item;
|
||||
// If the item is an object with name and email, format it
|
||||
if (item.name && item.email) return `"${item.name}" <${item.email}>`;
|
||||
// If the item is an object but doesn't match expected structure, stringify it
|
||||
return JSON.stringify(item);
|
||||
}).join(', ');
|
||||
return JSON.stringify(item); // Handle unexpected object format
|
||||
});
|
||||
} else if (typeof to === 'object' && to.email) {
|
||||
// Handle single object
|
||||
emails = [`"${to.name}" <${to.email}>`];
|
||||
} else {
|
||||
// Fallback for other types
|
||||
emails = [String(to)];
|
||||
}
|
||||
|
||||
// Fallback for any other types (unlikely but safe)
|
||||
return String(to);
|
||||
return emails; // Always returns an array
|
||||
}
|
||||
|
||||
|
||||
exports.SendEmail = async function (to, subject, text, html, attachments = []) {
|
||||
let sender = '"Специално Свидетелстване София - тест" <demo@mwitnessing.com>';
|
||||
to = Array.isArray(to) ? to : [to];
|
||||
const emailAddresses = normalizeEmailAddresses(to)
|
||||
|
||||
const message = {
|
||||
|
Reference in New Issue
Block a user