Home > Article > Web Front-end > How to send an email from a web page using JavaScript
With the development of the Internet, email has become an indispensable part of people's daily lives. In websites and applications, sending emails has become one of the problems that must be solved.
As a front-end programming language, JavaScript is widely used in web pages. If you are developing a JavaScript-based website or application, then you probably need to use JavaScript to send emails.
In this article, we will learn how to send emails from a web page using JavaScript. First, we need to choose an email service provider, in this case we choose to use Gmail as an example.
1. Enable Gmail’s SMTP service
First, we need to enable Gmail’s SMTP service. Go to the "Security" tab in your Gmail account settings and enable "Enable low-security apps."
In order to send emails using the Gmail SMTP server, we need to use the following details:
2. Sending emails using JavaScript
To send emails using JavaScript, we can use the SMTP client library. In this example we use Nodemailer library.
2.1. Install Nodemailer
Use the following command to install nodemailer in your project:
npm install nodemailer
2.2. Write JavaScript code
Let’s take a look How to write JavaScript code to send emails using Nodemailer. First, we need to create an SMTP transport object for sending emails to the Gmail server.
const nodemailer = require('nodemailer'); // 创建一个SMTP传输对象 const transporter = nodemailer.createTransport({ host: 'smtp.gmail.com', port: 465, secure: true, auth: { user: 'your@gmail.com', pass: 'yourpassword' } });
Next step we need to define an email options object, including the recipient address, content and subject of the email.
// 定义一个邮件选项对象 const mailOptions = { from: 'your@gmail.com', to: 'recipient@example.com', subject: '邮件主题', text: '邮件内容' };
Once we have defined the transport object and mail options object, we can use the transporter.sendMail method to send emails.
// 使用SMTP传输对象发送邮件 transporter.sendMail(mailOptions, (err, info) => { if (err) { console.log(err); } else { console.log(info); } });
Now we have successfully sent an email using JavaScript and Nodemailer. You can use the Mail Options object to send HTML emails or emails with attachments.
3. Summary
In this article, we introduced how to send emails in a web page using JavaScript and the Nodemailer library. We also saw how to use the Gmail SMTP server to send emails. However, please note that many email service providers may block sending emails from JavaScript clients due to security reasons. Be sure to understand the policies of your chosen email service provider before using it in your project.
The above is the detailed content of How to send an email from a web page using JavaScript. For more information, please follow other related articles on the PHP Chinese website!