Cookie Consent by Free Privacy Policy Generator 📌 Sending Emails Using Node.js


✅ Sending Emails Using Node.js


💡 Newskategorie: Programmierung
🔗 Quelle: dev.to

Introduction

In this guide, we'll explore how to send emails using Node.js with the help of Nodemailer, a module for Node.js applications to allow easy email sending.

Prerequisites

Before we dive into the code, ensure you have the following prerequisites:

  • Node.js installed on your system
  • An understanding of JavaScript and Node.js basics
  • An email account for sending emails
  • Basic knowledge of Express.js (optional)

Setting Up Nodemailer

First, install the Nodemailer package in your Node.js project using npm or yarn:

npm install nodemailer
npm install multer

Setting environment variables

Then, create a .env file in your project directory to store sensitive information like email credentials:

EMAIL_HOST=your_email_host
EMAIL_PORT=your_email_port
EMAIL_USERNAME=your_email_username
EMAIL_PASSWORD=your_email_password

Replace your_email_host, your_email_port, your_email_username, and your_email_password with your email provider's SMTP details.

Writing the Code

As in this example I am using Express.js we should make router and controller for our API. Lets start with router which will

Setting up Express Router

Now, let's write the Node.js code to send emails. Here's an example function using Express.js for handling email sending requests. In more advanced example I added middelware for validation and token verification, but we can skip it for now. If we want user to be able to attach files when sending email, we can use multer for easy file uploading.

// emailRoutes.js

const express = require('express');
const router = express.Router();
require('dotenv').config();
const verifyToken = require('../../middleware/verifyToken');
const upload = require('../../libs/multer');
const { emailSenderValidation, emailContactValidation } = require('../../middleware/mailerValidation');
const { sendNotifyPlainEmail } = require('../../controllers/email/emailController');

// POST route for sending notification emails with plain text
router.post('/notify/plain', upload.any('files'), verifyToken, emailSenderValidation, sendNotifyPlainEmail);

module.exports = router;

Controller Functions

Now, let's define the controller functions for handling email sending in emailController.js:

const nodemailer = require("nodemailer");
require('dotenv').config();
const path = require('path');
const { validationResult } = require('express-validator');
const { generateSimpleEmail, generateContactEmail } = require('./emailGenerator');

async function sendNotifyPlainEmail(req, res) {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    }
    const { to, cc, subject, content } = req.body;

    try {
        const transporter = nodemailer.createTransport({
            host: process.env.EMAIL_HOST,
            port: process.EMAIL_PORT,
            secure: true,
            auth: {
                user: process.env.EMAIL_USERNAME,
                pass: process.env.EMAIL_PASSWORD,
            },
            tls: {
                rejectUnauthorized: true,
            },
        });
        const haveAttachments = req?.files ? req.files.map(file => {
            return {
                filename: file?.originalname,
                path: path.join('uploads', file?.originalname),
                cid: file?.filename
            }
        }) : false;

        const info = await transporter.sendMail({
            from: '"Admin Test 🚀" <[email protected]>',
            to: to,
            cc: cc,
            subject: subject,
            text: content,
            html: content,
            attachments: haveAttachments ? haveAttachments : ''
        });
        console.log(info.envelope);
        console.log("Message sent: %s", info);
        res.send({ data: `Email sent to ${to}`, messageId: info.messageId }).status(200);
    } catch (exc) {
        console.error('error happened', exc);
        res.status(400).send({ message: `Message was not delivered to ${to}`, error: exc });
    }
}

module.exports = { sendNotifyPlainEmail };

Testing API

Ok now we have our API so we want to test it , easiest way to do is with postman or curl, here is the example for curl :

curl --location 'http://localhost:3000/email/notify/plain' \
--header 'x-api-key: 1111111-1111-111-1111-11111' \
--form 'to="[email protected]"' \
--form 'content="Test 123"' \
--form 'subject="Test Subject"'

After successfully calling our new API we should be able to see response

{"data":"Email sent to [email protected]","messageId":"<[email protected]>"}%        

Conclusion

With this code, you can easily send emails using Node.js and Nodemailer. Remember to handle errors gracefully and secure your email credentials properly.

Feel free to customize the code according to your specific requirements and integrate it into your Node.js applications for sending emails effortlessly.

Please leave your comments if you want part 2 where we will be sending email templates using mailer and be sure to checkout original post

Sending Emails Using Node.js

With Node.js, developers have a powerful tool at their disposal for automating tasks, including sending emails.

bojanjagetic.com
...

✅ Sending Emails Using Node.js


📈 34.91 Punkte

✅ Master Nodemailer: The Ultimate Guide to Sending Emails from Node.js


📈 30.34 Punkte

✅ Integrating SendGrid with Node.js for sending transactional emails


📈 30.34 Punkte

✅ Beginner’s Guide On Sending Automated Emails With Node.js, Nodemailer, and Cron Jobs


📈 30.34 Punkte

✅ Phorpiex Botnet Sending Out Millions of Sextortion Emails Using Hacked Computers


📈 27.27 Punkte

✅ Sending HTML emails without using third-party services


📈 27.27 Punkte

✅ Sending Email Using Node.js


📈 25.3 Punkte

✅ Sending Telegram Messages using Node.js and the Telegram API


📈 25.3 Punkte

✅ Sending Emails with React Email and Next.js


📈 22.7 Punkte

✅ Zero-Day Warning: It's Possible to Hack iPhones Just by Sending Emails


📈 22.7 Punkte

✅ Sending Emails with Python is too easy?


📈 22.7 Punkte

✅ Phishers are sending fake "Privacy Policy Update" emails


📈 22.7 Punkte

✅ Yahoo Mail not sending or receiving emails


📈 22.7 Punkte

✅ Two zero-day Flaws With Apple iPhones and iPads Let Attackers to Hack Devices Just by Sending Emails


📈 22.7 Punkte

✅ Microsoft Teams finally lets webinar organizers block the sending of attendee emails


📈 22.7 Punkte

✅ Buggy Microsoft Outlook Sending Encrypted S/MIME Emails With Plaintext Copy For Months


📈 22.7 Punkte

✅ Anti-virus firm McAfee seems to be sending junk emails


📈 22.7 Punkte

✅ Hacking Apple iPhones and iPads by sending emails to the victims


📈 22.7 Punkte

✅ Sending Emails Made Easy Integrating Nodemailer with Reactjs


📈 22.7 Punkte

✅ Woman arrested for sending phishing emails to US Politicians


📈 22.7 Punkte

✅ Mail.ru: [v7lk.relap.io] Sending arbitrary emails to any user


📈 22.7 Punkte

✅ Sending quick emails to team WADE is no sweat thanks to Duet AI in #GoogleWorkspace 🙌 #Ad


📈 22.7 Punkte

✅ Botnet Sending 5 Million Emails Per Hour to Spread Jaff Ransomware


📈 22.7 Punkte

✅ Amex Fined £90,000 for Sending Spam Emails


📈 22.7 Punkte

✅ Zero-Day Warning: It's Possible to Hack iPhones Just by Sending Emails


📈 22.7 Punkte

✅ Microsoft fixes Outlook Desktop crashes when sending emails


📈 22.7 Punkte

✅ Airline Fined For Sending 3.3 Million Unwanted Emails


📈 22.7 Punkte

✅ Amex Fined After Sending Over Four Million Spam Emails


📈 22.7 Punkte

✅ Why You Should Be Sending More Video Emails - BSW #154


📈 22.7 Punkte

✅ Microsoft shares temp fix for Outlook crashes when sending emails


📈 22.7 Punkte

✅ Spammer Faces Decades In Prison For Sending More Than 1 Million Spam Emails


📈 22.7 Punkte

✅ American Express (Amex) Fined £90,000 For Sending 4 Million Spam Emails Within a Year


📈 22.7 Punkte











matomo

Datei nicht gefunden!