Florian Burel
Florian Burel

Reputation: 3456

nodejs :send a mail via a custom smtp server

I have an SMTP server installed on my server, and I would like my nodejs app to be able to send a mail using it. This means basically running this command from node js:

echo "Hello" | mail -s "Test" [email protected]

I am aware that I could run said command, but is there maybe (hopefully) a cleaner way to do so? Thank you.

Upvotes: 5

Views: 6978

Answers (1)

Ridham Tarpara
Ridham Tarpara

Reputation: 6160

If you want to run any CLI command from the node.js to send mail then use shelljs to run a command from your app.

const shell = require('shelljs');
shell.exec('echo "Hello" | mail -s "Test" [email protected]')

But a good way is to use any mail sending a package.If you want to send emails from the node.js with your own SMTP server or an external server then Nodemailer is the best package to do so.

const nodemailer = require('nodemailer');

// Generate test SMTP service account from ethereal.email
// Only needed if you don't have a real mail account for testing
nodemailer.createTestAccount((err, account) => {

    // create reusable transporter object using the default SMTP transport
    let transporter = nodemailer.createTransport({
        host: 'smtp.ethereal.email',
        port: 587,
        secure: false, // true for 465, false for other ports
        auth: {
            user: account.user, // generated ethereal user
            pass: account.pass  // generated ethereal password
        }
    });

    // setup email data with unicode symbols
    let mailOptions = {
        from: '"Fred Foo 👻" <[email protected]>', // sender address
        to: '[email protected], [email protected]', // list of receivers
        subject: 'Hello ✔', // Subject line
        text: 'Hello world?', // plain text body
        html: '<b>Hello world?</b>' // html body
    };

    // send mail with defined transport object
    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log('Message sent: %s', info.messageId);
        // Preview only available when sending through an Ethereal account
        console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));

        // Message sent: <[email protected]>
        // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
    });
});

Upvotes: 7

Related Questions