Web project using Node.js to implement email sending function

WBOY
Release: 2023-11-08 14:57:00
Original
907 people have browsed it

Web project using Node.js to implement email sending function

Web project using Node.js to implement email sending function

With the rapid development of the Internet, email has become one of the important tools for people to communicate. In web development, sometimes we need to implement the function of sending emails, such as registration confirmation emails, password reset emails, etc. As an efficient server-side JavaScript running environment, Node.js can easily implement the email sending function. This article will introduce how to use Node.js to implement a web-based email sending project, and provide specific code examples.

1. Project environment setup

  1. Installing Node.js

First, we need to install Node.js locally. You can go to the Node.js official website (https://nodejs.org) to download the installation package for the corresponding operating system, and then install it according to the prompts.

  1. Initialize the project

Create a project directory locally and use the command line to enter the directory. Then run the following command to initialize the project:

npm init -y
Copy after login

This command will generate a configuration file named "package.json", which is used to manage the project's dependency packages.

  1. Install necessary modules

After the initialization is completed, we need to install some necessary Node.js modules, including express, nodemailer and body-parser. You can install it with the following command:

npm install express nodemailer body-parser
Copy after login

These modules are used to create a web server, send emails, and parse the request body of POST requests.

2. Write code

  1. Create an Express application

Create a file named "app.js" in the project directory and write The following code:

// 引入必要的模块 const express = require('express'); const bodyParser = require('body-parser'); const nodemailer = require('nodemailer'); // 创建Express应用 const app = express(); // 解析POST请求的请求体 app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // 定义发送邮件的路由 app.post('/sendmail', (req, res) => { // 获取请求参数 const { to, subject, text } = req.body; // 创建SMTP传输器 const transporter = nodemailer.createTransport({ service: 'Gmail', auth: { user: 'your-email@gmail.com', // 发件人邮箱 pass: 'your-password' // 发件人邮箱密码 } }); // 设置邮件内容 const mailOptions = { from: 'your-email@gmail.com', // 发件人 to, // 收件人 subject, // 邮件主题 text // 邮件正文 }; // 发送邮件 transporter.sendMail(mailOptions, (error, info) => { if (error) { console.log(error); res.status(500).send('邮件发送失败'); } else { console.log('邮件发送成功'); res.send('邮件发送成功'); } }); }); // 启动Web服务器 app.listen(3000, () => { console.log('服务器已启动'); });
Copy after login

In the above code, the necessary modules express, nodemailer and body-parser are first introduced. Then I created an Express application and defined a "/sendmail" route in the "app.js" file to receive POST requests and send emails. The email is sent using the nodemailer module, which is implemented by creating an SMTP transmitter.

  1. Start the Web server

Run the following command in the command line to start the Web server:

node app.js
Copy after login

3. Test the email sending function

Enter "http://localhost:3000" in the browser to enter the Web page. Then you can send an email through the following code:

fetch('http://localhost:3000/sendmail', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ to: 'recipient-email@example.com', // 收件人邮箱 subject: '测试邮件发送', // 邮件主题 text: '这是一封测试邮件' // 邮件正文 }) }) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log(error));
Copy after login

The above code uses the fetch function to send a POST request to the "http://localhost:3000/sendmail" route, and passes the recipient's email address, email subject, and The email body is used as a request parameter.

After running the above code, if the console outputs "Email sent successfully", it means the email was sent successfully.

Summary

This article introduces how to use Node.js to implement a web-based email sending project, and provides specific code examples. Through this project, we can easily implement the email sending function, and can expand and customize it according to our own needs. I hope this article will be helpful to readers who are new to Node.js and web development.

The above is the detailed content of Web project using Node.js to implement email sending function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!