📌  相关文章
📜  nodemailer (1)

📅  最后修改于: 2023-12-03 14:44:44.755000             🧑  作者: Mango

Nodemailer - A Node.js module for sending emails

Nodemailer is a powerful and flexible Node.js module designed for sending transactional emails. It can be easily integrated into any Node.js project to send emails directly from the application to the user's inbox. With Nodemailer, developers have greater control over the email sending process and can customize emails to include rich content, attachments, and more.

Key Features of Nodemailer
  • Supports many popular email services, including Gmail, Yahoo, Outlook, etc.
  • Provides SMTP transports for sending email messages.
  • Supports streaming RAM and File attachments.
  • Can work with transactional email services such as Mandrill and SendGrid.
  • Provides templates and plugins for generating dynamic email content.
Installing Nodemailer

To install the Nodemailer module to your Node.js project, run the following command:

npm install nodemailer
Basic Usage Example

To send an email message using Nodemailer, you first need to create a transporter object that defines your email service and the necessary authentication details. You can then create an email message and use the transporter object to send it.

Here's a code snippet that demonstrates this basic usage example:

const nodemailer = require('nodemailer');

// create reusable transporter object using SMTP transport
const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'your-email@gmail.com',
        pass: 'your-password'
    }
});

// setup email data with unicode symbols
let mailOptions = {
    from: 'your-email@gmail.com',
    to: 'recipient-email@example.com',
    subject: 'Hello ✔',
    text: 'Hello world?',
    html: '<b>Hello world?</b>'
};

// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        return console.log(error);
    }
    console.log('Message sent: %s', info.messageId);
});

This code creates a reusable transporter object that uses the SMTP transport protocol to send emails via a Gmail account. An email message is then created in the mailOptions object, and the transporter.sendMail method is used to send the message. If the email is successfully sent, the message ID is logged to the console.

Conclusion

Nodemailer is a powerful Node.js module that makes sending emails simple and easy. Its flexible API allows developers to customize every aspect of the email sending process, making it a great choice for any Node.js project.