nodejs如何验证邮箱是否可用
时间: 2023-08-22 15:08:56 浏览: 62
在 Node.js 中,可以使用第三方库 `nodemailer` 和 `dns` 来验证邮箱是否可用。
首先,需要安装 `nodemailer`:
```
npm install nodemailer
```
然后,可以使用以下代码来验证邮箱是否可用:
```js
const nodemailer = require('nodemailer');
const dns = require('dns');
const validateEmail = async (email) => {
// 获取邮箱域名
const domain = email.split('@')[1];
// 查询 MX 记录
let mxRecords;
try {
mxRecords = await dns.promises.resolveMx(domain);
} catch (error) {
console.error(error);
return false;
}
// 连接到 SMTP 服务器
const transporter = nodemailer.createTransport({
host: mxRecords[0].exchange,
port: 25,
secure: false,
ignoreTLS: true,
tls: {
rejectUnauthorized: false,
},
});
// 发送测试邮件
let info;
try {
info = await transporter.verify();
} catch (error) {
console.error(error);
return false;
}
// 关闭连接
transporter.close();
return true;
};
validateEmail('example@example.com')
.then(console.log)
.catch(console.error);
```
这个函数会返回一个 `Promise` 对象,如果邮箱可用则返回 `true`,否则返回 `false`。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)