mail-listener2:无法从对象获取字符串“地址”

时间:2018-08-11 14:40:39

标签: node.js

我正在使用mail-listener2从我的gmail帐户获取电子邮件。

我正在尝试从“ mail.to”对象获取字符串“地址”,但我却获得了“未定义”。有人可以帮我吗?

日志:

imapConnected
email: emailt.ost.ea.m.a.c.c.o@gmail.com
mail.to: [{"address":"emailt.ost.ea.m.a.c.c.o@gmail.com","name":""}]
mail.to typeof: object
MessageTo: undefined

代码:

const MailListener = require("mail-listener2");
const mailListener = new MailListener({
    username: "*",
    password: "*",
    host: "imap.gmail.com",
    port: 993,
    tls: true,
    connTimeout: 10000,
    authTimeout: 5000, 
    mailbox: "INBOX",
    searchFilter: ["UNSEEN"],
    markSeen: false,
    fetchUnreadOnStart: true
});

mailListener.start();
mailListener.on("server:connected", function(){
    console.log("imapConnected");
}); 
getCodeFromEmail('', 0, 10000, "emailt.ost.ea.m.a.c.c.o@gmail.com", function(code){
    console.log(code);
});
function getCodeFromEmail(string, offset, length, email, callback) {
    var callback = function(mail) {
        console.log("email: " + email);
        console.log("mail.to: " + JSON.stringify(mail.to));
        console.log("mail.to typeof: " + typeof mail.to)
        if(mail.to.address == email) {
            callback(mail.html.substr(mail.html.lastIndexOf(string) + offset, length));
            mailListener.removeListener('mail', callback);
        } else console.log("MessageTo: " + mail.to.address)
    };
    mailListener.on('mail', callback);
}

谢谢。

1 个答案:

答案 0 :(得分:1)

括号:

mail.to: [{"address":"emailt.ost.ea.m.a.c.c.o@gmail.com","name":""}]
         ^

建议mail.to是数组而不是对象。所以需要这样的东西:

mail.to[0].address