Home > Web Front-end > JS Tutorial > Mastering Email Sending in Node.js: A Step-by-Step Guide

Mastering Email Sending in Node.js: A Step-by-Step Guide

王林
Release: 2024-08-28 06:11:02
Original
336 people have browsed it

Mastering Email Sending in Node.js: A Step-by-Step Guide

Sending emails is a common feature in many web applications, whether it's for user registration, password resets, or marketing campaigns. In this guide, we'll show you how to send emails using Node.js with the help of the NodeMailer module. We'll cover everything from setting up your project to sending HTML emails and handling attachments.


1. Getting Started with Your Node.js Email Project

First, you'll need to set up a new Node.js project for sending emails.

  • Create a Project Folder
  mkdir emailtest
  cd emailtest
Copy after login
  • Initialize Your Project Create a package.json file with the following content:
  {
    "name": "emailtest",
    "version": "1.0.0",
    "main": "index.js",
    "dependencies": {
      "nodemailer": "^6.0.0"
    }
  }
Copy after login
  • Install NodeMailer Install the required NodeMailer module by running:
  npm install
Copy after login

2. Sending Your First Email

Now that your project is set up, let's send a simple email.

  • Create an index.js File Add the following code to send an email:
  import nodemailer from 'nodemailer';

  const transporter = nodemailer.createTransport({
    host: 'smtp.freesmtpservers.com',
    port: 25
  });

  const mailOptions = {
    from: '"Test Email" <test@email.com>',
    to: 'someone@example.com',
    subject: 'Hello!',
    text: 'Hello world!',
    html: '<p>Hello world!</p>'
  };

  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      console.log('Error:', error);
    } else {
      console.log('Email sent:', info.response);
    }
  });
Copy after login
  • Run Your Code Run the code using Node.js:
  node index.js
Copy after login

You should see a confirmation that the email was sent.


3. Adding Attachments to Your Email

If you need to send files with your email, NodeMailer makes it easy.

  • Example with Attachments
  const mailOptions = {
    from: '"Test Email" <test@email.com>',
    to: 'someone@example.com',
    subject: 'Hello with Attachments!',
    text: 'Please find the attached files.',
    attachments: [
      {
        filename: 'test.txt',
        path: './test.txt' // Local file
      },
      {
        filename: 'example.txt',
        content: 'This is a text file content.' // Content as string
      }
    ]
  };
Copy after login

4. Sending HTML Emails

HTML emails can make your messages more engaging with formatting, images, and links.

  • HTML Email Example
  const mailOptions = {
    from: '"Test Email" <test@email.com>',
    to: 'someone@example.com',
    subject: 'Hello, HTML!',
    html: '<h1>Hello world!</h1><p>This is an HTML email.</p>'
  };
Copy after login

5. Handling Errors

It's important to handle errors to ensure your application works smoothly.

  • Error Handling Example
  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      console.log('Error:', error.message);
    } else {
      console.log('Email sent:', info.response);
    }
  });
Copy after login

Conclusion

Sending emails using Node.js and NodeMailer is straightforward. With just a few lines of code, you can send plain text or HTML emails, attach files, and handle errors efficiently. As your needs grow, you can explore more advanced features like integrating with dedicated email services and managing asynchronous email queues.

The above is the detailed content of Mastering Email Sending in Node.js: A Step-by-Step Guide. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template