我正在尝试连接nodemailer以在注册后向用户发送邮件。 所以我在谷歌设置中打开了 IMAP,然后创建了应用程序来生成密码,并且这一切都适用于this Serivs。但是当我尝试连接邮件服务时,出现此错误
错误:连接ECONNREFUSED 127.0.0.1:587 在 TCPConnectWrap.afterConnect [作为未完成] (节点:net:1187:16) { 错误号:-111, 代码:'ESOCKET', 系统调用:'连接', 地址:'127.0.0.1', 端口:587, 命令:'CONN' }
邮件服务:
import nodemailer from "nodemailer";
class MailService {
constructor() {
this.transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: process.env.SMTP_PORT,
secure: false,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASSWORD,
},
});
}
async sendActicvationMail(to, link) {
await this.transporter.sendMail({
from: process.env.SMTP_USER,
to,
subject: "Mail activation " + process.env.API_URl,
text: "",
html: `
<div>
<h1>For activation click on link</h1>
<a href="${link}">Click here !</a>
</div>
`,
});
}
}
export default new MailService();
我可能在哪里犯错? 谢谢你!
丹尼尔
这段代码对我有用。但我配置了“使用应用程序密码登录”https://support.google.com/mail/answer/185833?hl=en-GB,因为nodemailer需要访问连接到gmail。接下来,我将 process.env.SMTP_PASSWORD 从 gmail 邮件的密码更改为“设备的应用程序密码” - 它看起来像 xxxx-xxxx-xxxx-xxxx 代码。
import nodemailer from "nodemailer";
import dotenv from 'dotenv';
class MailService {
constructor() {
dotenv.config();
this.transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: process.env.SMTP_PORT,
service: process.env.SMTP_SERVICE,
secure: true,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASSWORD,
},
});
}
async sendActivationMail(to, link) {
await this.transporter.sendMail({
from: process.env.SMTP_USER,
to,
subject: "Activation account" + process.env.API_URL,
text: "",
html: `
<div>
<h1>Activate your account, please</h1>
<a href="${link}">${link} </a>
</div>
`
});
}
};
export default new MailService();
我遇到了同样的问题,并在这个文件中使用了dotenv配置。
import nodemailer from "nodemailer";
// dotenv must be used
import dotenv from "dotenv";
dotenv.config();
// dotenv
class MailService {
constructor() {
this.transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: parseInt(process.env.SMTP_PORT, 10),
secure: false,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASSWORD,
},
});
}
async sendMail(email, activationLink) {
await this.transporter.sendMail({
from: process.env.SMTP_USER,
to: email,
subject: `Activation account link ${activationLink}`,
html: `
<div>
<a href="${activationLink}">Click to activate account</a>
</div>
`,
});
}
}
export default new MailService();