Dear all,
I’m facing an error with Maigun in a Netlify function. Everything works great in local, but when in production the mailing system is very inconsistent. Currently is Mailgun is not sending any email, but yesterday it was working.
The error in the Netlify Function Console is
11:35:00 AM: a81136dc INFO error: Error: Client network socket disconnected before secure TLS connection was established
at connResetException (internal/errors.js:609:14)
at TLSSocket.onConnectEnd (_tls_wrap.js:1549:19)
at Object.onceWrapper (events.js:420:28)
at TLSSocket.emit (events.js:326:22)
at endReadableNT (_stream_readable.js:1241:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: 'ECONNRESET',
path: null,
host: 'api.eu.mailgun.net',
port: 443,
localAddress: undefined
}
And the code of the function is:
const apiKey = '*xxxxxxxxxx*';
const domain = '*xxxxxxxxxxx*';
const mailgun = require('mailgun-js')({ apiKey, domain, host: "api.eu.mailgun.net" });
exports.handler = async (event, context) => {
try {
const body = JSON.parse(event.body)
const confirmationMailgun = body.confirmationMailgun;
const confirmationSubject = body.confirmationSubject;
const userName = body.userName;
const userEmail = body.userEmail;
const userPhone = body.userPhone;
const userMessage = body.userMessage;
if (event.httpMethod!='POST' || !event.body) {
return new Error('An error occurred!')
}
// ----------------------------------------
// NOTIFICATION: email sent to organization
// ----------------------------------------
const notificationVariables = {
userName,
userEmail,
userPhone,
userMessage,
};
// Add Notification Data
let notificationEmail = {
from: `${userName} <${userEmail}>`,
to: "hello@*xxxxxxxxxxxx*.com",
template: notificationMailgun,
subject: notificationSubject,
"h:X-Mailgun-Variables": JSON.stringify(notificationVariables)
}
// Send Notification Email
await mailgun.messages().send(notificationEmail, function (error) {
if (error) {
console.log('error:', error)
return error;
} else {
return {
statusCode: 200,
body: 'success'
};
}
});
// ----------------------------------------
// CONFIRMATION: email sent to organization
// ----------------------------------------
const confirmationVariables = {
userName,
userEmail,
userPhone,
userMessage,
};
// Add Notification Data
let confirmationEmail = {
from: "hello@*xxxxxxxxxxxx*.com",
to: `${userName} <${userEmail}>`,
template: confirmationMailgun,
subject: confirmationSubject,
"h:X-Mailgun-Variables": JSON.stringify(confirmationVariables)
}
// Send Notification Email
await mailgun.messages().send(confirmationEmail, function (error) {
if (error) {
console.log('error:', error)
return error;
} else {
return {
statusCode: 200,
body: 'success'
};
}
});
return { statusCode: 200, body: JSON.stringify({ message: 'Email Sent' }) };
} catch (err) {
console.error('Final Error:', err);
}
}
Thanks for your help!