commit 350a07b937babd547b2cef5de67ac18b608159e1
parent 467ecb68569eebbe24a2b27494a7d8e3f5fbaf5a
Author: AMIT DUTTA <amitdutta4255@gmail.com>
Date: Sun, 22 Feb 2026 14:43:00 +0530
Refactor email forwarding logic in server.js
Diffstat:
| M | server.js | | | 54 | +++++++++++++++++++++++------------------------------- |
1 file changed, 23 insertions(+), 31 deletions(-)
diff --git a/server.js b/server.js
@@ -5,11 +5,9 @@ const { Webhook } = require('svix');
const app = express();
const port = process.env.PORT || 3000;
-// Initialize Resend
const resend = new Resend(process.env.RESEND_API_KEY);
const webhookSecret = process.env.RESEND_WEBHOOK_SECRET;
-// We use express.text to get the raw string body needed for Svix verification
app.post('/api/incoming', express.text({ type: 'application/json' }), async (req, res) => {
try {
const rawBody = req.body;
@@ -19,78 +17,73 @@ app.post('/api/incoming', express.text({ type: 'application/json' }), async (req
'svix-signature': req.headers['svix-signature'],
};
- // 1. Verify Signature to prevent spam/abuse
const wh = new Webhook(webhookSecret);
let event;
try {
event = wh.verify(rawBody, headers);
} catch (err) {
- console.error('Webhook signature verification failed.', err.message);
+ console.error(err.message);
return res.status(400).json({ error: 'Invalid signature' });
}
- // 2. Ensure it's the right event
if (event.type !== 'email.received') {
return res.status(200).json({ message: 'Not an email event' });
}
- // 3. Extract data
const emailData = event.data;
const originalSender = emailData.from;
- const originalRecipient = emailData.to[0].toLowerCase(); // e.g., admin@amit.is-a.dev
+ const originalRecipient = emailData.to[0].toLowerCase();
const subject = emailData.subject || 'No Subject';
- // 4. Quota Protection (The Bouncer)
const allowedString = process.env.ALLOWED_ALIASES || '';
const allowedAliases = allowedString.split(',').map(alias => alias.trim().toLowerCase());
if (!allowedAliases.includes(originalRecipient)) {
- console.log(`Blocked email to unapproved alias: ${originalRecipient}`);
- // Return 200 OK so Resend doesn't retry
return res.status(200).json({ success: true, message: 'Alias ignored' });
}
- // 5. Forwarding Setup
const personalGmail = process.env.PERSONAL_GMAIL;
const forwardingAddress = process.env.FORWARDING_BOT_ADDRESS;
- // 6. Send the forwarded email
- const { data, error } = await resend.emails.send({
- from: `Dev Inbox <${forwardingAddress}>`,
+ const payload = {
+ from: `Forwarder <${forwardingAddress}>`,
to: [personalGmail],
replyTo: originalSender,
- subject: `[${originalRecipient.split('@')[0]}] ${subject}`,
- html: `
- <div style="background-color: #f3f4f6; padding: 12px; margin-bottom: 20px; border-radius: 6px; font-family: sans-serif; font-size: 14px; color: #374151;">
- <strong>From:</strong> ${originalSender}<br>
- <strong>To:</strong> ${originalRecipient}
- </div>
- ${emailData.html || `<p>${emailData.text}</p>` || '<p>No content.</p>'}
- `,
- text: `From: ${originalSender}\nTo: ${originalRecipient}\n\n${emailData.text || 'No content.'}`,
- });
+ subject: subject
+ };
+
+ if (emailData.html) {
+ payload.html = emailData.html;
+ }
+
+ if (emailData.text) {
+ payload.text = emailData.text;
+ }
+
+ if (!emailData.html && !emailData.text) {
+ payload.text = 'No content found in the original email.';
+ }
+
+ const { data, error } = await resend.emails.send(payload);
if (error) {
- console.error('Resend forward failed:', error);
+ console.error(error);
return res.status(500).json({ error: error.message });
}
- console.log(`Successfully forwarded email to ${personalGmail}`);
return res.status(200).json({ success: true, id: data?.id });
} catch (error) {
- console.error('Server error:', error);
+ console.error(error);
return res.status(500).json({ error: 'Internal Server Error' });
}
});
-// --- UPTIMEROBOT PING ROUTE ---
-// Point UptimeRobot to https://your-render-url.onrender.com/ping
app.get('/ping', (req, res) => {
res.status(200).send('Server is awake!');
});
app.listen(port, () => {
console.log(`Email router listening on port ${port}`);
-});-
\ No newline at end of file
+});