2013-08-05 4 views
1

Я не могу понять, как заставить nodemailer работать, я также добавил свои учетные данные для gmail и попробовал отправить электронное письмо самому себе, но он ничего мне не отправил, и он не ошибся, поэтому я смущен. Вполне возможно, что я пропускаю вещи из моего кода ...Как мне заставить nodemailer работать?

здесь файл по электронной почте:

var nodemailer = require('nodemailer'); 
var config = require('./config/config'); 

var smtpTransport = nodemailer.createTransport("SMTP",{ 
    service: "Gmail", 
    auth: { 
     user: config.mailer.auth.user, 
     pass: config.mailer.auth.pass 
    } 
}); 

var EmailAddressRequiredError = new Error('email address required'); 


exports.sendOne = function(templateName, locals, fn) { 
    if(!locals.email) { 
     return fn(EmailAddressRequiredError); 
    } 

    if(!locals.subject) { 
     return fn(EmailAddressRequiredError); 
    } 

    // template 
    var transport = smtpTransport; 
    transport.sendMail({ 
     from: config.mailer.defaultFromAddress, 
     to: locals.email, 
     subject: locals.subject, 
     html: html, 
     text: text 
    }, function (err, responseStatus) { 
     if(err) { 
      return fn(err); 
     } 
     return fn(null, responseStatus.message, html, text); 
    }); 

}; 

Вот файл маршрута отправки электронной почты:

exports.forgotPasswordPost = function(req, res, next) { 
    console.log("Forgot Password Post"); 
    if(req.body.email === '') { 
     console.log('err'); 
    } else { 
    crypto.randomBytes(48, function(ex, buf) { 
     var userToken = buf.toString('hex'); 
     console.log(userToken); 
     User.findOne({email: (req.body.email)}, function(err, usr) { 
      if(err || !usr) { 
       res.send('That email does not exist.');    
      } else { 
       console.log(usr); 
       //just call the usr found and set one of the fields to what you want it to be then save it and it will update accordingly 
       usr.token = userToken; 
       usr.tokenCreated = new Date(); 
       usr.save(function(err, usr){ 
       // res.redirect('login', {title: 'Weblio', message: 'Your token was sent by email. Please enter it on the form below.'}); 
        console.log(usr); 
       }); 

       console.log(usr); 
       var resetUrl = req.protocol + '://' + req.host + '/password_reset/' + usr.token; 
       console.log(resetUrl); 
       var locals = { 
       resetUrl: resetUrl, 
       }; 
       console.log(locals); 
       mailer.sendOne('password_reset', locals, function(err, email) { 
        console.log('email sent'); 
        res.redirect('successPost'); 
       }); 
      } 




     }); 
    }); 
    } 
}; 

Нужно ли мне что-нибудь еще, кроме того, что у меня есть?

+0

Вы можете разбить это вниз к меньшему воспроизводимый пример? И вы использовали пакетный сниффер, чтобы узнать, пытается ли ваше приложение даже отправить сообщение? – Brad

+0

Я пытаюсь отправить ссылку на сброс пароля, которая включает в себя токен пользователя пользователю. Это имеет смысл? Никогда не слышал о пакете сниффер, у вас есть ссылка на него? – Lion789

+0

Я говорю, что неважно, каковы ваши маршруты, токены пользователей, доступ к базе данных и т. Д. Сделайте простой воспроизводимый пример, который сужает проблему до просто nodemailer. Кроме того, ознакомьтесь с Wireshark. http://www.wireshark.org/download.html – Brad

ответ

-1

Я думаю, вам нужно указать на сервер gmail, а не на Gmail. Я забыл, что это точно, но sometihng как gmail.smtp

+0

Остальное все выглядит правильно? https://github.com/andris9/Nodemailer Это означает, что в противном случае – Lion789

1

Я не идентифицировал местных жителей правильно.

Это код, который работал для меня:

var nodemailer = require('nodemailer'); 
var config = require('./config/config'); 

var smtpTransport = nodemailer.createTransport("SMTP",{ 
    // host: "smtp.gmail.com", 
    // secureConnection: true, 
    // port: 465, 
    service: "Gmail", 
    //debug : true, 
    auth: { 
     user: config.mailer.auth.user, 
     pass: config.mailer.auth.pass 
    } 


}); 

var EmailAddressRequiredError = new Error('email address required'); 


exports.sendOne = function(template, locals, err) { 
    var message = { 
     from: config.mailer.defaultFromAddress, 
     to: locals.email, 
     subject: locals.subject, 
     html: locals.html, 
     text: locals.text 
    }; 
    console.log('hitlocal email'); 
    console.log(message); 
    //console.log(message.to.locals.email); 
    if(!locals.email) { 
    // console.log('email err'); 
    } 

    if(!locals.subject) { 
     console.log('subj err'); 
    } 

    // template 
    var transport = smtpTransport; 
    // console.log('hit here'); 
    // console.log(transport); 
    transport.sendMail(message, function(err) { 
     if(err) { 
      console.log('email js error'); 
      console.log(err); 
     } 
     console.log('Message sent') 

     //return fn(null, responseStatus.message, html, text); 
    }); 

}; 

И это файл маршруты:

var locals = { 
        email: 'first last <' + req.body.email + '>', 
        subject: 'Password Reset', 
        html: '<p> Please go to the following link to reset your password.' + resetUrl + '</p>', 
        text: 'Texty Text it' 
       }; 
       console.log('locals spot here'); 
       console.log(locals.email); 
       mailer.sendOne('forgotPassword', locals, function(err) { 

        console.log('email sent'); 

       }); 
Смежные вопросы