91 lines
2.2 KiB
JavaScript
91 lines
2.2 KiB
JavaScript
const path = require("path");
|
|
require("dotenv").config({
|
|
path: path.resolve(
|
|
process.cwd(),
|
|
`.env.${process.env.NODE_ENV || "development"}`
|
|
),
|
|
});
|
|
const axios = require("axios");
|
|
let nodemailer = require("nodemailer");
|
|
let aws = require("aws-sdk");
|
|
|
|
const ses = new aws.SES({
|
|
apiVersion: "2010-12-01",
|
|
region: "ca-central-1",
|
|
});
|
|
|
|
let transporter = nodemailer.createTransport({
|
|
SES: { ses, aws },
|
|
});
|
|
|
|
exports.sendEmail = async (req, res) => {
|
|
if (process.env.NODE_ENV !== "production") {
|
|
console.log("[EMAIL] Incoming Message", req.body.from.name);
|
|
}
|
|
|
|
let downloadedMedia = [];
|
|
if (req.body.media && req.body.media.length > 0) {
|
|
downloadedMedia = await Promise.all(
|
|
req.body.media.map((m) => {
|
|
try {
|
|
return getImage(m);
|
|
} catch (error) {
|
|
console.log(error);
|
|
}
|
|
})
|
|
);
|
|
}
|
|
|
|
transporter.sendMail(
|
|
{
|
|
from: `${req.body.from.name} <${req.body.from.address}>`,
|
|
replyTo: req.body.ReplyTo.Email,
|
|
to: req.body.to,
|
|
cc: req.body.cc,
|
|
subject: req.body.subject,
|
|
attachments:
|
|
[
|
|
...((req.body.attachments &&
|
|
req.body.attachments.map((a) => {
|
|
return {
|
|
filename: a.filename,
|
|
path: a.path,
|
|
};
|
|
})) ||
|
|
[]),
|
|
...downloadedMedia.map((a) => {
|
|
return {
|
|
path: a,
|
|
};
|
|
}),
|
|
] || null,
|
|
html: req.body.html,
|
|
ses: {
|
|
// optional extra arguments for SendRawEmail
|
|
Tags: [
|
|
{
|
|
Name: "tag_name",
|
|
Value: "tag_value",
|
|
},
|
|
],
|
|
},
|
|
},
|
|
(err, info) => {
|
|
console.log(err || info);
|
|
if (info) {
|
|
console.log("[EMAIL] Email sent: " + info);
|
|
res.json({ success: true, response: info });
|
|
} else {
|
|
console.log("[EMAIL] Email send failed. ", err);
|
|
res.json({ success: false, error: err });
|
|
}
|
|
}
|
|
);
|
|
};
|
|
|
|
async function getImage(imageUrl) {
|
|
let image = await axios.get(imageUrl, { responseType: "arraybuffer" });
|
|
let raw = Buffer.from(image.data).toString("base64");
|
|
return "data:" + image.headers["content-type"] + ";base64," + raw;
|
|
}
|