2014-10-04 5 views
11

Я установил локальный локальный узел NodeJS (используя модуль nodemailer) (http://localhost:8080), чтобы проверить, действительно ли сервер может отправлять электронные письма.Отправка электронной почты с помощью Node.js с помощью nodemailer не работает

Если я понимаю вариант SMTP правильно (пожалуйста, поправьте меня, если я ошибаюсь), я могу либо попытаться отправить электронную почту от моего сервера к чьей-то учетной записи электронной почты непосредственно, или я могу отправить по электронной почте , все еще используя Node.js, но через фактическую учетную запись электронной почты (в данном случае мою личную учетную запись Gmail), то есть используя SMTP. Этот параметр требует, чтобы я заходил на эту учетную запись удаленно через NodeJS.

Итак, на сервере ниже я фактически пытаюсь использовать NodeJs для отправки электронной почты с моей личной учетной записи электронной почты на мою личную учетную запись электронной почты.

Вот мой простой сервер:

var nodemailer = require('nodemailer'); 
var transporter = nodemailer.createTransport("SMTP", { 
    service: 'Gmail', 
    auth: { 
     user: '*my personal Gmail address*', 
     pass: '*my personal Gmail password*' 
    } 
}); 

var http = require('http'); 
var httpServer = http.createServer(function (request, response) 
{ 
    transporter.sendMail({ 
     from: '*my personal Gmail address*', 
     to: '*my personal Gmail address*', 
     subject: 'hello world!', 
     text: 'hello world!' 
    }); 
}).listen(8080); 

Однако, это не работает. Я получил письмо от Google, говоря:

Google Account: sign-in attempt blocked If this was you You can switch to an app made by Google such as Gmail to access your account (recommended) or change your settings at https://www.google.com/settings/security/lesssecureapps so that your account is no longer protected by modern security standards.

я не смог найти решение указанной задачи на GitHub странице nodemailer. Кто-нибудь имеет решение/предложение?

Спасибо! :-)

ответ

25

Ответ в сообщении от Google.

Для второй части проблемы, и в ответ на

I'm actually simply following the steps from the nodemailer github page so there are no errors in my code

Я отсылаю вас на страницу nodemailer GitHub, и этот кусок кода:

var transporter = nodemailer.createTransport({ 
service: 'Gmail', 
auth: { 
    user: '[email protected]mail.com', 
    pass: 'userpass' 
} 
}); 

Это немного отличается от кода, в том, что у вас есть: nodemailer.createTransport("SMTP". Удалите параметр SMTP, и он работает (только что протестирован). Кроме того, зачем инкапсулировать его на http-сервере? следующие работы:

var nodemailer = require('nodemailer'); 
var transporter = nodemailer.createTransport({ 
    service: 'Gmail', 
    auth: { 
     user: 'xxx', 
     pass: 'xxx' 
    } 
}); 

console.log('created'); 
transporter.sendMail({ 
from: '[email protected]', 
    to: '[email protected]', 
    subject: 'hello world!', 
    text: 'hello world!' 
}); 
+0

Я хотел бы избежать этого, думая, что это действительно может сделать мой счет более уязвима .. Я думал, что я мог бы обойти это с помощью некоторого параметра nodemailer, что я возможно, не обратил внимания. Возможно, установил некоторые дополнительные свойства сертификации. Спасибо, хотя! –

+0

Включив это сейчас, я знаю, что дольше получаю это уведомление от Google, но я не получаю сообщение по электронной почте, так что он все еще не работает. Я боюсь .. –

+0

попробуйте использовать другой адрес «от» и «от», у меня была аналогичная проблема в прошлом с gmail и любым другим получателем, чем я работал. – xShirase

2

Для отладки цели это удобно реализовать функцию обратного вызова (они никогда не делают на странице GitHub nodemailer), который показывает сообщение об ошибке (если есть один).

transporter.sendMail({ 
    from: from, 
    to: to, 
    subject: subject, 
    html: text 
}, function(err){ 
    if(err) 
     console.log(err); 
}) 

Это помогло мне решить мою проблему ... Оказывается, новые версии не работает должным образом:

«Похож nodemailer 1.0 имеет отличия так 0.7 должны быть использовано вместо: http://www.nodemailer.com/

Сообщения размещены на nodemailer от 12/17/15:

Не обновляйте Nodemailer от 0,7 или ниже 1,0, поскольку есть разбивающиеся изменения. Вы можете продолжать использовать ветвь 0,7, если хотите. Обратитесь к документации на 0.7 here «

Я нашел этот ответ here

0

попробовать этот код его работы для меня

var http = require('http'); 
var nodemailer = require('nodemailer'); 
http.createServer(function (req, res) { 
    res.writeHead(200, {'Content-Type': 'text/plain'}); 

    var fromEmail = '[email protected]'; 
    var toEmail = '[email protected]'; 

    var transporter = nodemailer.createTransport({ 
    host: 'domain', 
    port: 587, 
    secure: false, // use SSL 
    debug: true, 
     auth: { 
     user: '[email protected]', 
     pass: 'userpassword' 
     } 
    }); 
    transporter.sendMail({ 
     from: fromEmail, 
     to: toEmail, 
     subject: 'Regarding forget password request', 
     text: 'This is forget password response from youapp', 
     html: '<p>Your password is <b>sample</b></p>' 
    }, function(error, response){ 
     if(error){ 
      console.log('Failed in sending mail'); 
      console.dir({success: false, existing: false, sendError: true}); 
      console.dir(error); 
      res.end('Failed in sending mail'); 
     }else{ 
      console.log('Successful in sedning email'); 
      console.dir({success: true, existing: false, sendError: false}); 
      console.dir(response); 
      res.end('Successful in sedning email'); 
     } 
    }); 
}).listen(8000); 
console.log('Server listening on port 8000'); 

ответ:..

Successful in sedning email 
{ success: true, existing: false, sendError: false } 
{ accepted: [ '[email protected]' ], 
    rejected: [], 
    response: '250 2.0.0 uAMACW39058154 Message accepted for delivery', 
    envelope: 
    { from: '[email protected]', 
    to: [ '[email protected]' ] }, 
    messageId: '[email protected]' } 
7

Для тех, кто на самом деле хотите использовать OAuth2/не хотите, чтобы приложение было «менее безопасным», вы можете достичь этого на

  1. Поиск "Gmail API" из google API console и нажмите кнопку "Включить"
  2. Следуйте инструкциям на https://developers.google.com/gmail/api/quickstart/nodejs. В файле quickstart.js, изменяя SCOPES вар от ['https://www.googleapis.com/auth/gmail.readonly'] к ['https://mail.google.com/'] в файле QUICKSTART при условии, как расслоение плотной предложено в устранении неисправностей в https://nodemailer.com/smtp/oauth2/
  3. После выполнения действия, описанные в (2), созданный файл в формате JSON будет содержать acessToken, refreshToken, и expires атрибуты необходимы в OAuth2 Examples for Nodemailer

Таким образом, вы можете использовать OAuth2 аутентификации вроде следующего

let transporter = nodemailer.createTransport({ 
    service: 'Gmail', 
    auth: { 
     type: 'OAuth2', 
     user: '[email protected]', 
     clientId: '000000000000-xxx0.apps.googleusercontent.com', 
     clientSecret: 'XxxxxXXxX0xxxxxxxx0XXxX0', 
     refreshToken: '1/XXxXxsss-xxxXXXXXxXxx0XXXxxXXx0x00xxx', 
     accessToken: 'ya29.Xx_XX0xxxxx-xX0X0XxXXxXxXXXxX0x', 
     expires: 1484314697598 
    } 
}); 

вместо сохранения пароля gmail в текстовом виде и понижения безопасности в вашей учетной записи.

+0

Больше недействительно, accessToken и refreshToken больше не существует в этом файле – CaptRisky

+0

Чтобы заставить его работать, я использовал комбинацию этого определения транспорта ответа (без указания accessToken и истекает) и это сообщение, в котором используется игровая площадка google oauth для получения токена обновления: https: // medium.com/@ pandeysoni/nodemailer-service-in-node-js-using-smtp-and-xoauth2-7c638a39a37e – apricity

+0

У меня не было переменной SCOPES в моем gmail-nodejs-quickstart.json – Kirby

1

Хотя приведенные выше ответы действительно работают, я хотел бы указать, что вы можете снизить уровень безопасности с Gmail на следующие TWO шагов.

ШАГ # 1

Google Account: sign-in attempt blocked If this was you You can switch to an app made by Google such as Gmail to access your account (recommended) or change your settings at https://www.google.com/settings/security/lesssecureapps so that your account is no longer protected by modern security standards.

ШАГ # 2

In addition to enabling Allow less secure apps, you might also need to navigate to https://accounts.google.com/DisplayUnlockCaptcha and click continue.

3

я просто установить мой домен: smtp.gmail.com и она работает. Я использую VPS Vultr.

код:

const nodemailer = require('nodemailer'); 
const ejs = require('ejs'); 
const fs = require('fs'); 

let transporter = nodemailer.createTransport({ 
    host: 'smtp.gmail.com', 
    port: 465, 
    secure: true, 
    auth: { 
     user: '[email protected]', 
     pass: 'xxx' 
    } 
}); 

let mailOptions = { 
    from: '"xxx" <[email protected]>', 
    to: '[email protected]', 
    subject: 'Teste Templete ✔', 
    html: ejs.render(fs.readFileSync('e-mail.ejs', 'utf-8') , {mensagem: 'olá, funciona'}) 
}; 

transporter.sendMail(mailOptions, (error, info) => { 
    if (error) { 
     return console.log(error); 
    } 
    console.log('Message %s sent: %s', info.messageId, info.response); 
}); 

мой шаблон EJS (электронная почта.EJS):

<html> 
    <body> 
     <span>Esse é um templete teste</span> 
     <p> gerando com o EJS - <%=mensagem%> </p> 
    </body> 
</html> 

Убедитесь, что:

  • установить EJS: НПМ установки EJS --save
  • установить nodemailer: НПМ установки nodemailer --save
  • пинг до Smtp .gmail.com works: ping smtp.gmail.com
  • изменить xxx @ gmai l.com вашего GMAIL по электронной почте
  • изменений [email protected] на адрес электронной почты, который вы хотите отправить письмо
  • Enable less secure apps
  • Disable Captcha temporarily

имеет хороший день;)

1

Вам нужен только пароль для приложения для Google Auth, а затем замените свой пароль Google в коде. иди сюда https://myaccount.google.com/apppasswords

Пример кода:

const nodemailer = require('nodemailer'); 
var transporter = nodemailer.createTransport({ 
    service: "Gmail", 
    auth: { 
     user: '[email protected]', 
     pass: 'app password here' 
    } 
    }); 
transporter.sendMail(option, function(error, info){ 
    if (error) { 
     console.log(error); 
    } else { 
     console.log('Email sent: ' + info.response); 
    } 
}); 

screenshot

+0

не знаю почему, но это работает на localhost, а не на моей промежуточной среде –

Смежные вопросы