From 11d0eff863c7f3a31e6e80f16d5c66d533dfe0ec Mon Sep 17 00:00:00 2001 From: Fabien O'Carroll Date: Fri, 8 Nov 2019 11:13:43 +0700 Subject: [PATCH] Converted bulk email service to use mailgun no-issue --- core/server/services/bulk-email/index.js | 65 +++++++++++++++++------- 1 file changed, 46 insertions(+), 19 deletions(-) diff --git a/core/server/services/bulk-email/index.js b/core/server/services/bulk-email/index.js index 5813678791..03a4494f96 100644 --- a/core/server/services/bulk-email/index.js +++ b/core/server/services/bulk-email/index.js @@ -1,7 +1,33 @@ -// @ts-check -const mailService = require('../mail'); -const ghostMailer = new mailService.GhostMailer(); +const {URL} = require('url'); +const mailgun = require('mailgun-js'); +const configService = require('../../config'); const common = require('../../lib/common'); +let mailgunInstance; + +function createMailgun(config) { + const baseUrl = new URL(config.baseUrl); + + return mailgun({ + apiKey: config.apiKey, + domain: config.domain, + protocol: baseUrl.protocol, + host: baseUrl.host, + port: baseUrl.port, + endpoint: baseUrl.pathname + }); +} + +const config = configService.get('bulk-email'); + +if (!config || !config.mailgun) { + common.logging.warn(`Bulk email service is not configured`); +} else { + try { + mailgunInstance = createMailgun(config.mailgun); + } catch (err) { + common.logging.warn(`Bulk email service is not configured`); + } +} /** * An email address @@ -23,22 +49,23 @@ module.exports = { * @returns {Promise} A promise representing the success of the email sending */ async send(message, recipients, recipientData) { - for (const recipient of recipients) { - const messageToSend = Object.assign({}, message, { - to: recipient - }); - let unsubscribeUrl = ''; - if (recipientData && recipientData[recipient]) { - unsubscribeUrl = recipientData[recipient].unsubscribe_url; - } - messageToSend.html = messageToSend.html.replace('%recipient.unsubscribe_url%', unsubscribeUrl); - try { - await ghostMailer.send(messageToSend); - } catch (err) { - // @TODO log this somewhere with state? - common.logging.warn(`Oh no! an email failed to send :( ${recipient}`); - } + if (!mailgunInstance) { + return; + } + let fromAddress = message.from; + if (/@localhost$/.test(message.from)) { + fromAddress = 'localhost@example.com'; + common.logging.warn(`Rewriting bulk email from address ${message.from} to ${fromAddress}`); + } + try { + const messageData = Object.assign({}, message, { + to: recipients.join(', '), + from: fromAddress, + 'recipient-variables': recipientData + }); + await mailgunInstance.messages().send(messageData); + } catch (err) { + common.logging.error({err}); } - return true; } };