// // pages/bulk-email.js
// import { useState } from 'react';
// import Papa from 'papaparse';
// export default function BulkEmail() {
// const [file, setFile] = useState(null);
// const [subject, setSubject] = useState('');
// const [body, setBody] = useState('');
// const [recipients, setRecipients] = useState([]);
// const [loading, setLoading] = useState(false);
// const [log, setLog] = useState('');
// const handleFileChange = (e) => {
// const f = e.target.files?.[0];
// setFile(f);
// setLog('');
// if (!f) return;
// Papa.parse(f, {
// header: true,
// skipEmptyLines: true,
// complete: (results) => {
// // Expecting columns: email, name
// const rows = results.data
// .map((row) => ({
// email: String(row.email || '').trim(),
// name: row.name ? String(row.name).trim() : '',
// }))
// .filter((r) => r.email);
// setRecipients(rows);
// setLog(`Parsed ${rows.length} recipients from file.`);
// },
// error: (err) => {
// console.error(err);
// setLog('Failed to parse CSV file.');
// },
// });
// };
// const handleSubmit = async (e) => {
// e.preventDefault();
// if (!recipients.length) {
// setLog('No recipients loaded from file.');
// return;
// }
// if (!subject || !body) {
// setLog('Please enter subject and body.');
// return;
// }
// setLoading(true);
// setLog('Sending emails...');
// // Optional: simple personalization using {{name}} placeholder
// // This example sends one email to all in BCC, so only global body is used.
// // For per-recipient personalization, you would loop and send in chunks. [web:11]
// try {
// const res = await fetch('/api/send-bulk-email', {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify({
// recipients,
// subject,
// html: body,
// }),
// });
// const data = await res.json();
// if (!res.ok) {
// throw new Error(data.error || 'Failed to send emails');
// }
// setLog(`Emails submitted successfully. Status: ${data.data?.id || 'OK'}`);
// } catch (err) {
// console.error(err);
// setLog(`Error: ${err.message}`);
// } finally {
// setLoading(false);
// }
// };
// return (
//
//
Bulk Email Sender (CSV)
//
// 1. Export your Excel file as CSV with columns: email,name.
// 2. Upload file, set subject and HTML body, then send.
//
//
// {log && (
//
// {log}
//
// )}
//
// );
// }
// pages/bulk-email.js
import { useState } from 'react';
import Papa from 'papaparse';
export default function BulkEmail() {
const [file, setFile] = useState(null);
const [subject, setSubject] = useState('');
const [body, setBody] = useState('');
const [recipients, setRecipients] = useState([]);
const [manualInput, setManualInput] = useState(''); // manual emails textarea
const [loading, setLoading] = useState(false);
const [log, setLog] = useState('');
const parseManualRecipients = () => {
if (!manualInput.trim()) return [];
// Split by comma, semicolon, or newline
const raw = manualInput
.split(/[\n,;]+/)
.map((item) => item.trim())
.filter(Boolean);
const unique = Array.from(new Set(raw));
return unique.map((email) => ({
email,
name: '',
}));
};
const handleFileChange = (e) => {
const f = e.target.files?.[0] || null;
setFile(f);
setLog('');
if (!f) {
// if user clears file input, keep manual entries only
const manualRecipients = parseManualRecipients();
setRecipients(manualRecipients);
return;
}
Papa.parse(f, {
header: true,
skipEmptyLines: true,
complete: (results) => {
const rows =
results.data
?.map((row) => ({
email: String(row.email || '').trim(),
name: row.name ? String(row.name).trim() : '',
}))
.filter((r) => r.email) || [];
const manualRecipients = parseManualRecipients();
// merge CSV + manual, de-dupe by email
const all = [...rows, ...manualRecipients];
const dedupMap = new Map();
all.forEach((r) => {
if (!dedupMap.has(r.email)) {
dedupMap.set(r.email, r);
}
});
const merged = Array.from(dedupMap.values());
setRecipients(merged);
setLog(
`Parsed ${rows.length} recipients from file. Manual: ${manualRecipients.length}. Total unique: ${merged.length}.`
);
},
error: (err) => {
console.error(err);
setLog('Failed to parse CSV file.');
},
});
};
const handleManualBlur = () => {
// Update recipients whenever manual input loses focus
const manualRecipients = parseManualRecipients();
// keep any file recipients if file is present
if (!file) {
setRecipients(manualRecipients);
setLog(`Manual recipients: ${manualRecipients.length}.`);
return;
}
// if file recipients already loaded, merge with them
setRecipients((prev) => {
const all = [...prev, ...manualRecipients];
const dedupMap = new Map();
all.forEach((r) => {
if (!dedupMap.has(r.email)) {
dedupMap.set(r.email, r);
}
});
const merged = Array.from(dedupMap.values());
setLog(
`Recipients updated. Manual: ${manualRecipients.length}, Total unique: ${merged.length}.`
);
return merged;
});
};
const handleSubmit = async (e) => {
e.preventDefault();
const manualRecipients = parseManualRecipients();
let finalRecipients = recipients;
// if no file used but manual has data, use manual
if (!finalRecipients.length && manualRecipients.length) {
finalRecipients = manualRecipients;
setRecipients(manualRecipients);
}
if (!finalRecipients.length) {
setLog('No recipients found. Please upload CSV or enter emails manually.');
return;
}
if (!subject.trim() || !body.trim()) {
setLog('Please enter subject and body.');
return;
}
setLoading(true);
setLog('Sending emails...');
try {
const res = await fetch('/api/send-bulk-email', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
recipients: finalRecipients,
subject,
html: body,
}),
});
const data = await res.json();
if (!res.ok) {
throw new Error(data.error || 'Failed to send emails');
}
setLog(
`Emails submitted successfully. Status: ${data.data?.id || 'OK'}`
);
} catch (err) {
console.error(err);
setLog(`Error: ${err.message}`);
} finally {
setLoading(false);
}
};
return (
Bulk Email Sender
You can either upload a CSV file (email,name) or enter
email addresses manually (comma / semicolon / new line separated).
{log && (
{log}
)}
);
}