Created
December 21, 2023 07:49
-
-
Save theharithsa/cf820fa750a3bd945ad4bf3ac71e1747 to your computer and use it in GitHub Desktop.
Script to send an email by parsing the received JSON from the internet or locally.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const nodemailer = require('nodemailer'); | |
const app = express(); | |
app.use(express.json()); | |
app.post('/send-email', (req, res) => { | |
const { toEmail, subject, jsonData } = req.body; | |
console.log("Received JSON data:", req.body.jsonData); | |
const htmlContent = generateHtmlTable(jsonData); | |
// Set up the transporter | |
const transporter = nodemailer.createTransport({ | |
host: 'smtp.office365.com', // Replace with your SMTP server address | |
port: 587, // Common ports are 587 (for TLS) or 465 (for SSL) | |
secure: false, // Set to true if using SSL, false if using TLS | |
auth: { | |
user: 'admin@dt-transform.com', | |
pass: '<password>' | |
}, | |
tls: { | |
// Only necessary if the server uses self-signed certificates | |
rejectUnauthorized: false | |
} | |
}); | |
const mailOptions = { | |
from: 'admin@dt-transform.com', | |
to: toEmail, | |
subject: subject, | |
html: htmlContent | |
}; | |
transporter.sendMail(mailOptions, function (error, info) { | |
if (error) { | |
console.log(error); | |
res.status(500).send('Error sending email'); | |
} else { | |
console.log('Email sent: ' + info.response); | |
res.status(200).send('Email sent successfully'); | |
} | |
}); | |
}); | |
function generateHtmlTable(jsonData) { | |
let html = '<table style="border-collapse: collapse; width: 100%;">'; | |
// Add table headers | |
if (jsonData.length > 0) { | |
html += '<tr>'; | |
Object.keys(jsonData[0]).forEach(key => { | |
html += `<th style="border: 1px solid black; padding: 8px; text-align: left;">${key}</th>`; | |
}); | |
html += '</tr>'; | |
} | |
// Add table rows | |
jsonData.forEach(item => { | |
html += '<tr>'; | |
Object.values(item).forEach(value => { | |
html += `<td style="border: 1px solid black; padding: 8px;">${value}</td>`; | |
}); | |
html += '</tr>'; | |
}); | |
html += '</table>'; | |
return html; | |
} | |
const PORT = 3000; | |
app.listen(PORT, () => { | |
console.log(`Server running on port ${PORT}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment