所以我试图通过node.js发送自己的IP地址,到目前为止空手而归。到目前为止,我的代码看起来像这样:
var exec = require("child_process").exec;
var ipAddress = exec("ifconfig | grep -m 1 inet", function (error, stdout, stderr) {
ipAddress = stdout;
});
var email = require('nodemailer');
email.SMTP = {
host: 'smtp.gmail.com',
port: 465,
ssl: true,
user_authentication: true,
user: 'sendingemail@gmail.com',
pass: 'mypass'
}
email.send_mail({
sender: 'sendingemail@gmail.com',
to: 'receivingemail@gmail.com',
subject: 'Testing!',
body: 'IP Address of the machine is ' + ipAddress
},
function(error, success) {
console.log('Message ' + success ? 'sent' : 'failed');
console.log('IP Address is ' + ipAddress);
process.exit();
}
);
到目前为止,它正在发送电子邮件,但它从不插入IP地址。它将适当的IP地址放在我可以看到的控制台日志中,但无法通过电子邮件发送它。任何人都可以帮我看看我的代码中出错了吗?
答案 0 :(得分:0)
这是因为send_mail
函数在exec
返回ip之前开始。
所以只要exec返回ip就开始发送邮件。
这应该有效:
var exec = require("child_process").exec;
var ipAddress;
var child = exec("ifconfig | grep -m 1 inet", function (error, stdout, stderr) {
ipAddress = stdout;
start();
});
var email = require('nodemailer');
function start(){
email.SMTP = {
host: 'smtp.gmail.com',
port: 465,
ssl: true,
user_authentication: true,
user: 'sendingemail@gmail.com',
pass: 'mypass'
}
email.send_mail({
sender: 'sendingemail@gmail.com',
to: 'receivingemail@gmail.com',
subject: 'Testing!',
body: 'IP Address of the machine is ' + ipAddress
},
function(error, success) {
console.log('Message ' + success ? 'sent' : 'failed');
console.log('IP Address is ' + ipAddress);
process.exit();
}
);
}