【问题标题】:Send IP Address in email with node.js使用 node.js 在电子邮件中发送 IP 地址
【发布时间】:2026-01-21 01:00:01
【问题描述】:

所以我试图通过 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 地址放在我可以看到的控制台日志中,但无法让它通过电子邮件发送。谁能帮我看看我在代码中做错了什么?

【问题讨论】:

标签: email node.js ip-address


【解决方案1】:

那是因为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();
       }
    );
}

【讨论】:

  • 是的,这就像一个魅力!非常感谢,你可能会说我真的不知道我在用 node.js 做什么:-)