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 logger = require("../utils/logger"); 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) => { logger.log("send-email", "DEBUG", req.user.email, null, { 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, }); 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) { logger.log("send-email-error", "ERROR", req.user.email, null, { 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, 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) { logger.log("send-email-success", "DEBUG", req.user.email, null, { 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, info, }); res.json({ success: true, response: info }); } else { logger.log("send-email-failure", "ERROR", req.user.email, null, { 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, error: 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; }