Logo

dev-resources.site

for different kinds of informations.

Simple Emails Sending from Node.js Using Nodemailer and SMTP

Published at
9/8/2024
Categories
node
nodemailer
emailsending
Author
shivaji_zirpe
Categories
3 categories in total
node
open
nodemailer
open
emailsending
open
Author
13 person written this
shivaji_zirpe
open
Simple Emails Sending from Node.js Using Nodemailer and SMTP

When building a web application, sending automated emails is a crucial feature for tasks like account verification, password resets, or notifications. my name is Shivaji Zirpe and In this blog post, we’ll explore how you can achieve this in your Node.js application using Nodemailer and SMTP.

What is Nodemailer?

Nodemailer is a popular Node.js library that makes sending emails easy. It supports various email services such as Gmail, Outlook, and custom SMTP servers.

Setting Up an SMTP Server

Before we dive into the implementation, ensure you have the following:

  1. SMTP Server Details: These are typically provided by your email service provider.
  2. SMTP Authentication Credentials: This includes the email address and password used to send emails.

Step-by-Step Implementation

1. Install Nodemailer

In your Node.js project, install Nodemailer using npm:

npm install nodemailer
Enter fullscreen mode Exit fullscreen mode

2. Create a Mail Transporter

In your project, set up a transporter using SMTP. The transporter handles the communication with the mail server:

const nodemailer = require('nodemailer');

// Create a transporter
const transporter = nodemailer.createTransport({
  host: process.env.SMTP_HOST, // SMTP host, e.g., smtp.mailprovider.com
  port: process.env.SMTP_PORT || 587, // Port (587 for TLS, 465 for SSL)
  secure: process.env.SMTP_PORT == 465, // Use SSL for port 465
  auth: {
    user: process.env.EMAIL_USERNAME, // SMTP username
    pass: process.env.EMAIL_PASSWORD, // SMTP password
  },
});
Enter fullscreen mode Exit fullscreen mode

In this code:

  • host: Specifies the SMTP host provided by your email service.
  • port: Use 587 for TLS or 465 for SSL.
  • secure: Set to true if you’re using port 465 (SSL).
  • auth: Your SMTP username and password for authentication.

3. Create Mail Options

Next, we create the mailOptions object, which holds the details of the email, such as sender, receiver, subject, and content:

const mailOptions = {
  from: process.env.EMAIL, // Sender's email address
  to: '[email protected]', // Recipient's email address
  subject: "Your Subject", // Email subject
  html: `<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Your Title</title>
</head>
<body style="font-family: Helvetica, Arial;">
  <div>Here is your email content</div>
</body>
</html>`, // HTML content of the email
};
Enter fullscreen mode Exit fullscreen mode
  • from: Specifies the sender’s email.
  • to: Defines the recipient’s email.
  • subject: Contains the subject of the email.
  • html: The body of the email in HTML format, which can be customized with images, links, and styling.

4. Send the Email

Now that the transporter and mail options are ready, let's send the email:

transporter.sendMail(mailOptions, (error, info) => {
  if (error) {
    console.error("Error sending email:", error);
  } else {
    console.log("Email sent successfully:", info.response);
  }
});
Enter fullscreen mode Exit fullscreen mode

This code attempts to send the email. If there’s an error, it will be logged; otherwise, the email is sent successfully.

Environment Variables

It's important to keep sensitive information like SMTP credentials secure by storing them in environment variables. Create a .env file in your project root and include the following:

EMAIL=your_email
EMAIL_PASSWORD=your_password
SMTP_HOST=smtp.mailprovider.com
SMTP_PORT=587
EMAIL=your_email
Enter fullscreen mode Exit fullscreen mode

Ensure that your application loads the environment variables using the dotenv package:

npm install dotenv
Enter fullscreen mode Exit fullscreen mode

Then load it at the top of your file:

require('dotenv').config();
Enter fullscreen mode Exit fullscreen mode

Conclusion

Integrating email functionality into your Node.js application using Nodemailer and SMTP is a great way to manage automated emails for your app. Whether it's for transactional emails, marketing campaigns, or user notifications, this setup provides a flexible and straightforward approach.

Key Points:

  • Nodemailer simplifies the process of sending emails in Node.js.
  • Storing credentials in environment variables protects sensitive data.
  • HTML emails allow for customization with rich content and design.

With this setup, you're now ready to send emails from your Node.js application via any SMTP server!

Feel free to leave questions in the comments, and don’t forget to follow for more tutorials and checking out some of my work on GitHub or visiting my Portfolio. also connect over LinkedIn!


#Nodejs #Nodemailer #SMTP #EmailService #WebDevelopment

nodemailer Article's
30 articles in total
Favicon
Brevo smtp emails to other gmail accounts silently failing , verified domain to the rescue
Favicon
Send emails using Nodemailer (Typescript)
Favicon
Simple Emails Sending from Node.js Using Nodemailer and SMTP
Favicon
Practical Guide to Send Emails from NodeJS/Express App using Gmail and Nodemailer (Screenshots and Code)
Favicon
Sending Emails in NextJs via Nodemailer
Favicon
Sending Emails in Node.js Using Nodemailer
Favicon
Sending e-mails with Sendgrid
Favicon
NestJS Emails with react-email and nodemailer
Favicon
nodeMailer after google security update
Favicon
Beginner’s Guide On Sending Automated Emails With Node.js, Nodemailer, and Cron Jobs
Favicon
Tracking Email Activity from AWS Simple Email Service (SES)
Favicon
Envio de email com NodeJS e Gmail
Favicon
Setting up Node.js Email Server with Nodemailer and Mailtrap
Favicon
Sending Emails from a Nodejs Application using Nodemailer
Favicon
Dynamic emails with handlebars and nodemailer
Favicon
Sending e-mails with Mailtrap
Favicon
Simple Next.JS Form to Email Using React-Hook-Form and Gmail
Favicon
How to send Email with NodeJS in 2022
Favicon
How to send email attachments using nodemailer
Favicon
Send emails from your website to any user super easily!
Favicon
How to Send an Email with Nodemailer
Favicon
Send email using next.js, react-hook-form, tailwindcss & nodemailer
Favicon
Nextjs - Nodemailer - React Hook Form - Tailwindcss
Favicon
How to send mail using Nodemailer?
Favicon
I created my own email server to send emails into my gmail for My Portfolio
Favicon
How to send mail using nodemailer in Angular 11?
Favicon
How I met your...Scraper?
Favicon
Отправка писем в NestJS используя nodemailer. Публикация скриптов.
Favicon
3 ways to send emails with only few lines of code and Gmail - Javascript - Part 1
Favicon
NodeJS – Send email by Nodemailer

Featured ones: