2012-03-26 74 views
1

因此,我试图通过node.js发送自己的IP地址,到目前为止都出现空手。到目前为止,我的代码如下所示:发送邮件的IP地址与node.js

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: '[email protected]', 
    pass: 'mypass' 
} 

email.send_mail({ 
    sender: '[email protected]', 
    to: '[email protected]', 
    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

为什么要使用“执行”,而不是'os.networkInterfaces'这是跨操作系统? 来源:http://nodejs.org/docs/latest/api/os.html#os_os_networkinterfaces – seppo0010 2012-03-26 20:48:58

回答

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: '[email protected]', 
     pass: 'mypass' 
    } 

    email.send_mail({ 
     sender: '[email protected]', 
     to: '[email protected]', 
     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(); 
     } 
    ); 
} 
+0

是的,这工程就像一个魅力!非常感谢,因为您可能知道我真的不知道我在做什么node.js :-) – noiz77 2012-03-26 07:53:50

+0

不客气!每一个开始都很难:D – stewe 2012-03-26 08:01:42

相关问题