gpt4 book ai didi

javascript - Nodemailing 使用变量发送带有 Javascript Discord 机器人的电子邮件

转载 作者:行者123 更新时间:2023-11-30 19:58:32 28 4
gpt4 key购买 nike

我正在尝试使用 Nodemailer 使 Discord 机器人根据信息向某些人发送电子邮件。我正在使用变量来选择向谁发送电子邮件。每当我尝试使用它时,它都无法发送电子邮件并说变量未定义。这是我的代码:

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")

最佳答案

var mailOptions = {
from: 'someemail@gmail.com',
to: firstname + "." + lastname + "@gmail.com",
subject: 'Sending Email using Node.js',
text: 'That was easy!'
};

这部分在它被解析时被评估——在其余代码运行之前,所以在 firstnamelastname 被填充之前(或者甚至被初始化为 "").它不会随着这些变量的变化而动态更新。

既然您想从根本上动态构造 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){
/* ... */

关于javascript - Nodemailing 使用变量发送带有 Javascript Discord 机器人的电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53654411/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com