Nodemailer отправить электронную почту без smtp транспорта

Я пытаюсь отправить электронную почту через nodemailer без транспорта SMTP. Поэтому я сделал это:

var mail = require("nodemailer").mail;

mail({
    from: "Fred Foo ✔ <[email protected]>", // sender address
    to: "******@gmail.com", // list of receivers
    subject: "Hello ✔", // Subject line
    text: "Hello world ✔", // plaintext body
    html: "<b>Hello world ✔</b>" // html body
});

Но когда я бегу, я получаю это:

> node sendmail.js
Queued message #1 from [email protected], to [email protected]
Retrieved message #1 from the queue, reolving gmail.com
gmail.com resolved to gmail-smtp-in.l.google.com for #1
Connecting to gmail-smtp-in.l.google.com:25 for message #1
Failed processing message #1
Message #1 requeued for 15 minutes
Closing connection to the server

Error: read ECONNRESET
    at errnoException (net.js:901:11)
    at TCP.onread (net.js:556:19)

Я на windows 7 32.

ИЗМЕНИТЬ  Это похоже на ошибку, связанную с Windows, поскольку она работала над linux

РЕДАКТИРОВАТЬ № 2

В оболочке git, если я введу telnet smtp.gmail 587, он заблокирован здесь:

220 mx.google.com ESMTP f7...y.24 -gsmtp

Ответы

Ответ 1

Из вашего примера вывода, похоже, подключается к неправильному порту 25, открытые порты gmail smtp - 465 для SSL и другие 587 TLS.

Nodemailer обнаруживает правильную конфигурацию на основе домена электронной почты, в вашем примере вы не установили объект транспортера, чтобы он настроил порт 25 по умолчанию. Чтобы изменить порт, укажите в параметрах тип.

Вот небольшой пример, который должен работать с gmail:

var nodemailer = require('nodemailer');

// Create a SMTP transport object
var transport = nodemailer.createTransport("SMTP", {
        service: 'Gmail',
        auth: {
            user: "[email protected]",
            pass: "Nodemailer123"
        }
    });

console.log('SMTP Configured');

// Message object
var message = {

    // sender info
    from: 'Sender Name <[email protected]>',

    // Comma separated list of recipients
    to: '"Receiver Name" <[email protected]>',

    // Subject of the message
    subject: 'Nodemailer is unicode friendly ✔', 

    // plaintext body
    text: 'Hello to myself!',

    // HTML body
    html:'<p><b>Hello</b> to myself <img src="cid:[email protected]"/></p>'+
         '<p>Here\ a nyan cat for you as an embedded attachment:<br/></p>'
};

console.log('Sending Mail');
transport.sendMail(message, function(error){
  if(error){
      console.log('Error occured');
      console.log(error.message);
      return;
  }
  console.log('Message sent successfully!');

  // if you don't want to use this transport object anymore, uncomment following line
  //transport.close(); // close the connection pool
});

Ответ 2

использовать nodemailer 0.7.1.
если вы ранее установили nodemailer, то удалите его с помощью

npm remove nodemailer

теперь установите его

npm install [email protected]

следующий код отправляет почту без входа в систему, но он будет работать только в рабочей среде, он не будет работать локально

var mail = require("nodemailer").mail;

mail({
    from: "Fred Foo ✔ <[email protected]>", // sender address
    to: "[email protected], [email protected]", // list of receivers
    subject: "Hello ✔", // Subject line
    text: "Hello world ✔", // plaintext body
    html: "<b>Hello world ✔</b>" // html body
});

Ответ 3

возможно, это брандмауэр Windows или антивирус, предотвращающий исходящий доступ. попробуйте включить отладочные сообщения nodemailer.

Включение отладки

var nodemailer = require("nodemailer"),
  transport = nodemailer.createTransport('direct', {
    debug: true, //this!!!
  });

transport.sendMail({
    from: "Fred Foo ✔ <[email protected]>", // sender address
    to: "******@gmail.com", // list of receivers
    subject: "Hello ✔", // Subject line
    text: "Hello world ✔", // plaintext body
    html: "<b>Hello world ✔</b>" // html body
}, console.error);

Ответ 4

Похоже, что текущий nodemailer не имеет возможности отправлять почту без smtp. Я бы порекомендовал взглянуть на библиотеку sendmail, в которой НЕ нужен smtp/auth для отправки электронной почты, Это дает вам аналогичный опыт использования sendmail в Linux.

const sendmail = require('sendmail')();

sendmail({
  from: '[email protected]',
  to: '[email protected]',
  subject: 'Hello World',
  html: 'Hooray NodeJS!!!'
}, function (err, reply) {
  console.log(err && err.stack)
  console.dir(reply)
})

Вы также можете включить silent, чтобы сделать его менее подробным: const sendmail = require('sendmail')({silent: true});. Следует заметить, что отправителем не могут быть те домены, в которых DMARC политика, как [email protected].

Ответ 5

Вам нужен SMTP-сервер, почтовый сервер, который пересылает электронные письма от вашего имени. Поэтому либо настройте собственный SMTP-сервер, например Haraka, либо предоставите учетные данные Nodemailer для подключения к одному, например. Gmail, MSN, Yahoo. Даже я начал изучать NodeJs и пытался включить функцию электронной почты в свой проект, и это была та же проблема, с которой я столкнулся.