Node.js Email with Notes and Examples

Using email in a Node.js application involves sending and receiving emails.

In this tutorial, you will learn working with Emails using Node.js

Sending Email

  1. Sending email involves sending messages from your Node.js application to recipients. You can use an SMTP server or email service to achieve this.
  2. Sending email with Node.js can be done with the nodemailer library.
const nodemailer = require('nodemailer');

    const transporter = nodemailer.createTransport({
      service: 'Gmail',
      auth: {
        user: 'youremail@gmail.com',
        pass: 'yourpassword',
      },
    });
    
    const mailOptions = {
      from: 'youremail@gmail.com',
      to: 'recipient@example.com',
      subject: 'Hello, from Node.js!',
      text: 'This is a plain text email sent from Node.js.',
    };
    
    transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
        console.log('Error:', error);
      } else {
        console.log('Email sent:', info.response);
      }
    });
    

Receiving Email

  1. Receiving email in Node.js generally involves accessing email from a mailbox using protocols like IMAP or POP3.
  2. const Imap = require('imap');
    
    const imap = new Imap({
        user: 'youremail@gmail.com',
        password: 'yourpassword',
        host: 'imap.gmail.com',
        port: 993,
        tls: true,
    });
    
    imap.once('ready', () => {
        imap.openBox('INBOX', true, (err, box) => {
        if (err) throw err;
        const fetch = imap.seq.fetch('1:5', { bodies: '' });
        fetch.on('message', (msg, seqno) => {
            msg.on('body', (stream, info) => {
            let buffer = '';
            stream.on('data', (chunk) => {
                buffer += chunk.toString('utf8');
            });
            stream.on('end', () => {
                console.log(buffer);
            });
            });
        });
        });
    });
    
    imap.connect();
            

Email Libraries

  1. To work with email in Node.js, you can use libraries like nodemailer for sending emails and imap or pop3 for receiving them.

Handling Attachments

  1. You can send email attachments, such as files or images, using email libraries like nodemailer.