Convert Figma logo to code with AI

nodemailer logonodemailer

✉️ Send e-mails with Node.JS – easy as cake!

16,963
1,376
16,963
16

Top Related Projects

2,195

html emails and attachments to any smtp server with nodejs

The Official Twilio SendGrid Led, Community Driven Node.js API Library

Quick Overview

Nodemailer is a popular Node.js module that provides a simple and efficient way to send emails from within a Node.js application. It supports a wide range of email service providers, including Gmail, Outlook, and custom SMTP servers, and offers a variety of features for customizing the email content and delivery.

Pros

  • Ease of Use: Nodemailer provides a straightforward and intuitive API for sending emails, making it easy to integrate into any Node.js project.
  • Flexibility: The library supports a wide range of email service providers, allowing developers to choose the one that best fits their needs.
  • Customization: Nodemailer offers extensive options for customizing the email content, including the ability to send HTML emails, attach files, and more.
  • Reliability: The library is well-maintained and widely used, with a large community of developers contributing to its development and providing support.

Cons

  • Dependency on Email Service Providers: Nodemailer relies on external email service providers, which can introduce additional complexity and potential points of failure.
  • Limited Error Handling: The library's error handling can be somewhat limited, making it challenging to diagnose and troubleshoot issues with email delivery.
  • Potential Security Concerns: Improper configuration or use of Nodemailer can lead to security vulnerabilities, such as email spoofing or unauthorized access to email accounts.
  • Learning Curve: While Nodemailer is relatively easy to use, developers may need to invest some time in understanding its features and best practices, especially when dealing with more complex email scenarios.

Code Examples

Here are a few examples of how to use Nodemailer to send emails:

  1. Sending a Basic Email:
const nodemailer = require('nodemailer');

async function sendEmail() {
  const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      user: 'your-email@gmail.com',
      pass: 'your-password'
    }
  });

  const mailOptions = {
    from: 'your-email@gmail.com',
    to: 'recipient-email@example.com',
    subject: 'Test Email',
    text: 'This is a test email sent using Nodemailer.'
  };

  try {
    await transporter.sendMail(mailOptions);
    console.log('Email sent successfully!');
  } catch (error) {
    console.error('Error sending email:', error);
  }
}

sendEmail();
  1. Sending an HTML Email with Attachments:
const nodemailer = require('nodemailer');
const fs = require('fs');

async function sendHTMLEmail() {
  const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      user: 'your-email@gmail.com',
      pass: 'your-password'
    }
  });

  const mailOptions = {
    from: 'your-email@gmail.com',
    to: 'recipient-email@example.com',
    subject: 'HTML Email with Attachments',
    html: '<h1>Hello, World!</h1><p>This is an HTML email sent using Nodemailer.</p>',
    attachments: [
      {
        filename: 'example.txt',
        content: fs.createReadStream('path/to/example.txt')
      },
      {
        filename: 'image.png',
        path: 'path/to/image.png'
      }
    ]
  };

  try {
    await transporter.sendMail(mailOptions);
    console.log('Email sent successfully!');
  } catch (error) {
    console.error('Error sending email:', error);
  }
}

sendHTMLEmail();
  1. Sending Emails with Dynamic Templates:
const nodemailer = require('nodemailer');
const handlebars = require('handlebars');
const fs = require('fs');

async function sendTemplatedEmail() {
  const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {

Competitor Comparisons

2,195

html emails and attachments to any smtp server with nodejs

Pros of emailjs

  • Simpler API with fewer configuration options, making it easier for beginners
  • Built-in support for popular email services like Gmail and Outlook
  • Lightweight package with minimal dependencies

Cons of emailjs

  • Less actively maintained compared to Nodemailer
  • Limited advanced features and customization options
  • Smaller community and fewer resources available

Code Comparison

Nodemailer:

const nodemailer = require('nodemailer');

let transporter = nodemailer.createTransport({
  host: 'smtp.example.com',
  port: 587,
  auth: { user: 'user@example.com', pass: 'password' }
});

let info = await transporter.sendMail({
  from: 'sender@example.com',
  to: 'receiver@example.com',
  subject: 'Test Email',
  text: 'Hello, this is a test email!'
});

emailjs:

const email = require('emailjs');

let server = email.server.connect({
  user: 'user@example.com',
  password: 'password',
  host: 'smtp.example.com',
  ssl: true
});

server.send({
  from: 'sender@example.com',
  to: 'receiver@example.com',
  subject: 'Test Email',
  text: 'Hello, this is a test email!'
}, (err, message) => { console.log(err || message); });

Both libraries provide similar functionality for sending emails, but Nodemailer offers more advanced features and configuration options, while emailjs focuses on simplicity and ease of use.

The Official Twilio SendGrid Led, Community Driven Node.js API Library

Pros of sendgrid-nodejs

  • Specialized for SendGrid's email service, offering seamless integration
  • Provides advanced features like email tracking and analytics
  • Robust API with comprehensive documentation

Cons of sendgrid-nodejs

  • Limited to SendGrid's service, less flexible for other email providers
  • May have higher costs associated with SendGrid's pricing tiers
  • Steeper learning curve for developers new to SendGrid's ecosystem

Code Comparison

sendgrid-nodejs:

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
  to: 'recipient@example.com',
  from: 'sender@example.com',
  subject: 'Hello World',
  text: 'This is a test email from SendGrid',
};
sgMail.send(msg);

Nodemailer:

const nodemailer = require('nodemailer');
let transporter = nodemailer.createTransport({
  host: 'smtp.example.com',
  port: 587,
  auth: { user: 'user@example.com', pass: 'password' }
});
transporter.sendMail({
  from: 'sender@example.com',
  to: 'recipient@example.com',
  subject: 'Hello World',
  text: 'This is a test email from Nodemailer'
});

Both libraries offer straightforward ways to send emails, but sendgrid-nodejs is more tightly integrated with SendGrid's services, while Nodemailer provides greater flexibility in choosing email providers and configuration options.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Nodemailer

Nodemailer

Send emails from Node.js – easy as cake! 🍰✉️

NPM

See nodemailer.com for documentation and terms.

[!TIP] Check out EmailEngine – a self-hosted email gateway that allows making REST requests against IMAP and SMTP servers. EmailEngine also sends webhooks whenever something changes on the registered accounts.

Using the email accounts registered with EmailEngine, you can receive and send emails. EmailEngine supports OAuth2, delayed sends, opens and clicks tracking, bounce detection, etc. All on top of regular email accounts without an external MTA service.

Having an issue?

First review the docs

Documentation for Nodemailer can be found at nodemailer.com.

Nodemailer throws a SyntaxError for "..."

You are using an older Node.js version than v6.0. Upgrade Node.js to get support for the spread operator. Nodemailer supports all Node.js versions starting from Node.js@v6.0.0.

I'm having issues with Gmail

Gmail either works well, or it does not work at all. It is probably easier to switch to an alternative service instead of fixing issues with Gmail. If Gmail does not work for you, then don't use it. Read more about it here.

I get ETIMEDOUT errors

Check your firewall settings. Timeout usually occurs when you try to open a connection to a firewalled port either on the server or on your machine. Some ISPs also block email ports to prevent spamming.

Nodemailer works on one machine but not in another

It's either a firewall issue, or your SMTP server blocks authentication attempts from some servers.

I get TLS errors

  • If you are running the code on your machine, check your antivirus settings. Antiviruses often mess around with email ports usage. Node.js might not recognize the MITM cert your antivirus is using.
  • Latest Node versions allow only TLS versions 1.2 and higher. Some servers might still use TLS 1.1 or lower. Check Node.js docs on how to get correct TLS support for your app. You can change this with tls.minVersion option
  • You might have the wrong value for the secure option. This should be set to true only for port 465. For every other port, it should be false. Setting it to false does not mean that Nodemailer would not use TLS. Nodemailer would still try to upgrade the connection to use TLS if the server supports it.
  • Older Node versions do not fully support the certificate chain of the newest Let's Encrypt certificates. Either set tls.rejectUnauthorized to false to skip chain verification or upgrade your Node version
let configOptions = {
    host: "smtp.example.com",
    port: 587,
    tls: {
        rejectUnauthorized: true,
        minVersion: "TLSv1.2"
    }
}

I have issues with DNS / hosts file

Node.js uses c-ares to resolve domain names, not the DNS library provided by the system, so if you have some custom DNS routing set up, it might be ignored. Nodemailer runs dns.resolve4() and dns.resolve6() to resolve hostname into an IP address. If both calls fail, then Nodemailer will fall back to dns.lookup(). If this does not work for you, you can hard code the IP address into the configuration like shown below. In that case, Nodemailer would not perform any DNS lookups.

let configOptions = {
    host: "1.2.3.4",
    port: 465,
    secure: true,
    tls: {
        // must provide server name, otherwise TLS certificate check will fail
        servername: "example.com"
    }
}

I have an issue with TypeScript types

Nodemailer has official support for Node.js only. For anything related to TypeScript, you need to directly contact the authors of the type definitions.

I have a different problem

If you are having issues with Nodemailer, then the best way to find help would be Stack Overflow or revisit the docs.

License

Nodemailer is licensed under the MIT No Attribution license


The Nodemailer logo was designed by Sven Kristjansen.

NPM DownloadsLast 30 Days