In Node.js possiamo inviare e-mail usando un server locale con Nodemailer.
Se l'MTA locale รจ correttamente configurato, le impostazioni di base di Nodemailer saranno le seguenti:
'use strict';
module.exports = {
smtp: {
from: 'your@email.tld',
settings: {
host: 'localhost',
port: 25
}
}
};
Quindi possiamo racchiudere la logica dell'invio dell'e-mail in una classe dedicata che faccia uso delle Promise.
'use strict';
const nodemailer = require('nodemailer');
class Mail {
constructor({ from, settings }) {
this.settings = settings;
this.options = {
from: from,
to: '',
subject: '',
text: '',
html: ''
};
}
send({to, subject, body}) {
if(nodemailer && this.options) {
let self = this;
const transporter = nodemailer.createTransport(self.settings);
self.options.to = to;
self.options.subject = subject;
self.options.text = body;
if(transporter !== null) {
return new Promise((resolve, reject) => {
transporter.sendMail(self.options, (error, info) => {
if(error) {
reject(Error('Failed'));
} else {
resolve('OK');
}
});
});
}
}
}
}
module.exports = Mail;
A questo punto possiamo usare la nostra classe come segue.
'use strict';
const Mail = require('./classes/Mail');
const { from, settings } = require('./config').smtp;
const sendMail = async ({ to, subject, body }) => {
const mail = new Mail({ from, settings });
try {
await mail.send({ to, subject, body });
return true;
} catch(err) {
return false;
}
};
La funzione sendMail() accetta come parametro un oggetto letterale contenente il destinatario, l'oggetto ed il messaggio dell'e-mail da inviare. Viene dichiarata come asincrona per sfruttare la Promise usata nella classe Mail e restituisce un valore booleano per analogia con l'implementazione presente in PHP.