如何在节点JS中使用NodeMailer发送邮件?
#javascript #编码 #expressjs #mail

文件夹结构:

Folder Structure of Output

app.js代码:

const express = require('express');
const ejs = require('ejs');
const transporter = require("./config/emailConfig.js");

const app = express();
const PORT = 8000;

// Set Template Engine 
app.set('view engine', 'ejs')
app.use(express.urlencoded({extended: false}))

app.get("/", (req, res) => {
    return res.render("index");
});

app.post("/", async (req, res) => {
    const { email } = req.body;

    try {
        let info = await transporter.sendMail({
            from: "laughtercomedy708@gmail.com", // sender address
            to: email, // list of receivers
            subject: "Express - Nodemailer", // Subject line
            text: " Email Send Successfuly.", // plain text body
        })
        return res.json({ "status": "success", "message": "Password Reset Email Sent... Please Check your Email."})
    } catch (error) {
        return res.json({ "status1": "failed", "message": error.message })
    }
})

app.listen(PORT, () => {
    console.log(`Server is Listening at ${PORT} Port.`);
})

package.json代码:

{
  "name": "q.11",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "dev": "nodemon app"
  },
  "keywords": [],
  "author": "aksh desai",
  "license": "ISC",
  "dependencies": {
    "ejs": "^3.1.8",
    "express": "^4.18.2",
    "nodemailer": "^6.8.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.20"
  }
}

emailconfig.js代码: -

const nodemailer = require("nodemailer");

let transporter = nodemailer.createTransport({
    host: "smtp.gmail.com",
    port: 587,
    // secure: false, // true for 465, false for other ports
    auth: {
        user: "laughtercomedy708@gmail.com", // generated ethereal user
        pass: "your app password", // generated ethereal password
    }
})

module.exports = transporter;

index.ejs代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1> Hello World </h1>

    <form action="/" method="post"> 
        <input type="email" name="email" required> <br>
        <input type="submit" value="submit">
    </form>

</body>
</html>

输出图像: -

Output Image

谢谢。
您可以关注我们:
Youtube
Instagram