我正试图使Discord机器人根据使用Nodemailer的信息向某些人发送电子邮件。我正在使用变量来选择向谁发送电子邮件。每当我尝试使用它时,它都无法发送电子邮件,并指出变量未定义。这是我的代码:
const Discord = require('discord.js');
const client = new Discord.Client();
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'user',
pass: 'pass'
}
});
var mailOptions = {
from: 'someemail@gmail.com',
to: firstname + "." + lastname + "@gmail.com",
subject: 'Sending Email using Node.js',
text: 'That was easy!'
};
var firstname = "";
var lastname = "";
var chat = 0;
var placeholder = "";
client.on("message", message => {
var prefix = '!';
if (message.content.startsWith(prefix + "chat") && chat == 0) {
chat = chat + 1;
message.channel.send("Welcome! I am Sabrina, a friendly chatbot. By the way, what is your first name?");
} else if (message.content.startsWith(prefix + "chat") && chat == 1) {
chat = chat + 1;
placeholder = message.content;
firstname = placeholder.replace("!chat ", "");
message.channel.send("Very intresting name, " + firstname + ".
What is your last name?");
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
}
});
}
});
client.login("Token")
答案 0 :(得分:1)
var mailOptions = {
from: 'someemail@gmail.com',
to: firstname + "." + lastname + "@gmail.com",
subject: 'Sending Email using Node.js',
text: 'That was easy!'
};
这部分在解析时进行评估-在其余代码运行之前,因此在firstname
和lastname
填充之前(甚至初始化为""
)。这些变量更改时不会动态更新。
既然您本质上想动态构造mailOptions
,为什么不创建一个能做到这一点的函数呢?
// Traditional syntax
function getMailOptions(first, last) {
return {
from: 'someemail@gmail.com',
to: first + "." + last + "@gmail.com",
subject: 'Sending Email using Node.js',
text: 'That was easy!'
}
}
// Or, since you're using arrow functions..
const getMailOptions = (first, last) => ({
from: 'someemail@gmail.com',
to: first + "." + last + "@gmail.com",
subject: 'Sending Email using Node.js',
text: 'That was easy!'
});
现在您可以使用它:
transporter.sendMail(getMailOptions(firstname, lastname), function(error, info){
/* ... */