EzDevInfo.com

Nodemailer

Send e-mails with Node.JS – easy as cake! E-mail made in Estonia Nodemailer by andris9

Nodemailer SES API vs SMTP

I've writing bulk email script in node.js that uses Amazon SES.

The scripts divides a large list into queues and each queue is executed separately. For each queue I use a different connection (even though it's none blocking) since I'm waiting on the response before i proceed to the next email in the queue.

I can connect and send via amazon SES using their API or using SMTP. I would assume that both methods will keep the connection open for the entire queue.

I was wondering if one has any advantages over the other. Is there any advantage in performance in favor of the API or the SMTP?


Source: (StackOverflow)

Not able to connect to outlook.com SMTP using Nodemailer

I am creating the transport object like this.

var transport = nodemailer.createTransport("SMTP", {
        host: "smtp-mail.outlook.com", // hostname
        secureConnection: false, // use SSL
        port: 587, // port for secure SMTP
        auth: {
            user: "user@outlook.com",
            pass: "password"
        }
    });

This is the error which I am getting, when I try to send the mail.

[Error: 139668100495168:error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number:../deps/openssl/openssl/ssl/s3_pkt.c:337: ]

When I tried setting ignoreTLS as true. This is what I am getting

{ [AuthError: Invalid login - 530 5.7.0 Must issue a STARTTLS command first] name: 'AuthError', data: '530 5.7.0 Must issue a STARTTLS command first' }

Am I doing something wrong? Please help.


Source: (StackOverflow)

Advertisements

Nodemailer with Gmail and NodeJS

I try to use nodemailer to implement a contact form using NodeJS but it works only on local it doesn't work on a remote server...

My error message :

[website.fr-11 (out) 2013-11-09T15:40:26] { [AuthError: Invalid login - 534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbvlX
[website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 V-dFQLgb7aRCYApxlOBuha5ESrQEbRXK0iVtOgBoYeARpm3cLZuUS_86kK7yPis7in3dGC
[website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 N1sqhr3D2IYxHAN3m7QLJGukwPSZVGyhz4nHUXv_ldo9QfqRydPhSvFp9lnev3YQryM5TX
[website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 XL1LZuJL7zCT5dywMVQyWqqg9_TCwbLonJnpezfBLvZwUyersknTP7L-VAAL6rhddMmp_r
[website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 A_5pRpA> Please log in via your web browser and then try again.
[website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 Learn more at https://support.google.com/mail/bin/answer.py?answer=787
[website.fr-11 (out) 2013-11-09T15:40:26] 534 5.7.14 54 fr4sm15630311wib.0 - gsmtp]
[website.fr-11 (out) 2013-11-09T15:40:26]   name: 'AuthError',
[website.fr-11 (out) 2013-11-09T15:40:26]   data: '534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbvlX\r\n534-5.7.14 V-dFQLgb7aRCYApxlOBuha5ESrQEbRXK0iVtOgBoYeARpm3cLZuUS_86kK7yPis7in3dGC\r\n534-5.7.14 N1sqhr3D2IYxHAN3m7QLJGukwPSZVGyhz4nHUXv_ldo9QfqRydPhSvFp9lnev3YQryM5TX\r\n534-5.7.14 XL1LZuJL7zCT5dywMVQyWqqg9_TCwbLonJnpezfBLvZwUyersknTP7L-VAAL6rhddMmp_r\r\n534-5.7.14 A_5pRpA> Please log in via your web browser and then try again.\r\n534-5.7.14 Learn more at https://support.google.com/mail/bin/answer.py?answer=787\r\n534 5.7.14 54 fr4sm15630311wib.0 - gsmtp',
[website.fr-11 (out) 2013-11-09T15:40:26]   stage: 'auth' }

My controller :

exports.contact = function(req, res){
    var name = req.body.name;
    var from = req.body.from;
    var message = req.body.message;
    var to = '*******@gmail.com';
    var smtpTransport = nodemailer.createTransport("SMTP",{
        service: "Gmail",
        auth: {
            user: "******@gmail.com",
            pass: "*****"
        }
    });
    var mailOptions = {
        from: from,
        to: to, 
        subject: name+' | new message !',
        text: message
    }
    smtpTransport.sendMail(mailOptions, function(error, response){
        if(error){
            console.log(error);
        }else{
            res.redirect('/');
        }
    });
}

Source: (StackOverflow)

Mocking email function in nodejs

I've got a mailer function I've built and trying to shore up the coverage. Trying to test parts of it have proven tricky, specifically this mailer.smtpTransport.sendMail

var nodemailer = require('nodemailer')

var mailer = {}

mailer.smtpTransport = nodemailer.createTransport('SMTP', {
    'service': 'Gmail',
    'auth': {
        'XOAuth2': {
            'user': 'test@test.com',
            'clientId': 'googleClientID',
            'clientSecret': 'superSekrit',
            'refreshToken': '1/refreshYoSelf'
        }
    }
})
var mailOptions = {
    from: 'Some Admin <test@tester.com>',
}

mailer.verify = function(email, hash) {
    var emailhtml = 'Welcome to TestCo. <a rel='nofollow' href="'+hash+'">Click this '+hash+'</a>'
    var emailtxt = 'Welcome to TestCo. This  is your hash: '+hash
    mailOptions.to = email
    mailOptions.subject = 'Welcome to TestCo!'
    mailOptions.html = emailhtml
    mailOptions.text = emailtxt
    mailer.smtpTransport.sendMail(mailOptions, function(error, response){
        if(error) {
            console.log(error)

        } else {
            console.log('Message sent: '+response.message)
        }
    })
}

I'm unsure of how to go about testing, specifically ensuring that my mailer.smtpTransport.sendMail function is passing the correct parameters without actually sending the email. I'm trying to use https://github.com/whatser/mock-nodemailer/tree/master, but I'm probably doing it wrong. Should I be mocking out the method?

var _ = require('lodash')
var should = require('should')
var nodemailer = require('nodemailer')
var mockMailer = require('./helpers/mock-nodemailer')
var transport = nodemailer.createTransport('SMTP', '')

var mailer = require('../../../server/lib/account/mailer')

describe('Mailer', function() {
    describe('.verify()', function() {
        it('sends a verify email with a hashto an address when invoked', function(done) {
            var email ={
                'to': 'dave@testco.com',
                'html': 'Welcome to Testco. <a rel='nofollow' href="bleh">Click this bleh</a>',
                'text': 'Welcome to Testco. This  is your hash: bleh',
                'subject': 'Welcome to Testco!'
            }

            mockMailer.expectEmail(function(sentEmail) {
            return _.isEqual(email, sentEmail)
            }, done)
            mailer.verify('dave@testco.com','bleh')
            transport.sendMail(email, function() {})
    })
})

Source: (StackOverflow)

POST request not allowed - 405 Not Allowed - nginx, even with headers included

I have a problem in trying to do a POST request in my application and I searched a lot, but I did not find the solution.

So, I have a nodeJS application and a website, and I am trying to do a POST request using a form from this site, but I always end up in this:

enter image description here

and in the console I see :

    Uncaught TypeError: Cannot read property 'value' of null 
Post "http://name.github.io/APP-example/file.html " not allowed

that is in this line of code :

file.html:

<form id="add_Emails" method ="POST" action="">

    <textarea rows="5" cols="50" name="email">Put the emails here...
    </textarea>

        <p>
        <INPUT type="submit" onclick="sendInvitation()" name='sendInvitationButton' value ='Send Invitation'/>
        </p>


</form>

<script src="scripts/file.js"></script>

file.js:

function sendInvitation(){

    var teammateEmail= document.getElementById("email").value;

I read many post and a documentation of cross domain but it did not work. research source 1:http://enable-cors.org/server.html research source 2: http://www.w3.org/TR/2013/CR-cors-20130129/#http-access-control-max-age

What I am doing now:

I am trying to POST from a different domain of my server :

POST REQUEST : http://name.github.io/APP-example/file.html , github repository

POST LISTENER : "http://xxx.xxx.x.xx:9000/email , server localhost ( x-> my ip address)

So, I had the same problem in other files, but I fixed it putting this code in the begginning of each route:

var express = require('express');
var sha1 = require('sha1'); 

var router = express.Router(); 
var sessionOBJ = require('./session');

var teams = {} 
var teamPlayers = []

router.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT, GET,POST");
  next();
 });

and I fixed it doing it.

Now, I am having the same problem, but in this file the only difference is that I deal with SMTP and emails, so I post an email and send an Email to this email I received in the POST request.

THe code is working totally fine with POSTMAN, so, when I test with POSTMAN it works and I can post.

I included this code below instead of the first one I showed but it did not work as well:

router.all('*', function(req, res, next){
            res.header("Access-Control-Allow-Origin", "*")
            res.header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
            res.header("Access-Control-Allow-Headers", "Origin, Content-Type, Accept")
            res.header("Access-Control-Max-Age", "1728000")
            next();
        });

Does someone know how to solve it?

Thank you.


Source: (StackOverflow)

Sending email attachments with Meteor.js (email package and/or nodemailer or otherwise)

Sending email attachments doesn't appear to be implemented yet in Meteor's official email package. I've tried the nodemailer suggestion (seen here) but received the error "Cannot read property 'createTransport' of undefined".

I'm attempting to create a CSV file in a data URI and then send that attachment. Here's a snippet of my code when using the official email package:

csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);

var options = {
          from: "xxx@gmail.com",
          to: "xxx@gmail.com",
          subject: "xxx",
          html: html,
          attachment: {
            fileName: fileName, 
            path: csvData
            }
      };

Meteor.call('sendEmail', options);

EDIT:

Here is basically what my nodemailer code looked like:

var nodemailer = Nodemailer;
var transporter = nodemailer.createTransport();
transporter.sendMail({
    from: 'sender@address',
    to: 'receiver@address',
    subject: 'hello',
    text: 'hello world!',
    attachments: [
        {   
            path: csvData
        }
    ]
});

Source: (StackOverflow)

Amazon SES nodemailer connection failing

I'm using nodejs nodemailer to connect to Amazon SES email service. It all appears simple, but I keep getting the error:

"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details."

I've already searched online and most people say it is because you have a space at the end of your secrect key or sometimes the forward slash maybe causing the problem. The last one is no longer an issue as I kept creating SMTP credentials until there wasn't one. I've created around 10 SMTP credentials now, copied and pasted the AccessKey and SecretKey in each time and I'm still getting this error. I've also tried using http://email-smtp.us-west-2.amazonaws.com as well and still got the same error.

Here is my code:

var nodemailer = require("nodemailer");
var transport = nodemailer.createTransport("SES", 
{
    AWSAccessKeyID: 'AKIA************',
    AWSSecretKey: 'AqlwF*****************************',
    SeviceUrl: 'http://email-smtp.us-east-1.amazonaws.com'
});
nodemailer.sendMail({
    transport : transport,
    sender : 'some@thing.com' ,
    to : 'another@address.com',
    subject : 'TEST',
    html: '<p> Hello World </p>'
}, function(error, response)
{
    if(error){ console.log(error); }   
    else{ console.log("Message sent: " + response.message);}
});

Anyone know what else I can do?


Source: (StackOverflow)

What is correct way of using Nodemailer in expressjs?

I am trying to use nodemailer in expressjs app. Should I keep creating of transport object out of route handler or creating transport object inside route handler is just fine?

var express = require('express')
  , app = express()
  , nodemailer = require('nodemailer');

  smtpTrans = nodemailer.createTransport('SMTP', {
      service: 'Gmail',
      auth: {
          user: "me@gmail.com",
          pass: "application-specific-password" 
      }
  });
  app.post('/register', function(req, res){
    smtpTrans.sendMail(mailOptions);
  });

or

var express = require('express')
  , app = express()
  , nodemailer = require('nodemailer');

  app.post('/register', function(req, res){
    smtpTrans = nodemailer.createTransport('SMTP', {
      service: 'Gmail',
      auth: {
          user: "me@gmail.com",
          pass: "application-specific-password" 
      }
    });
    smtpTrans.sendMail(mailOptions);
  });

Source: (StackOverflow)

Nodemailer: ECONNREFUSED

I don't know what I'm missing, I use the Nodemailer example:

var nodemailer = require("nodemailer");

// create reusable transport method (opens pool of SMTP connections)
var smtpTransport = nodemailer.createTransport("SMTP",{
    service: "Gmail",
    auth: {
        user: "gmail.user@gmail.com",
        pass: "userpass"
    }
});

// setup e-mail data with unicode symbols
var mailOptions = {
    from: "Fred Foo ✔ <foo@blurdybloop.com>", // sender address
    to: "bar@blurdybloop.com, baz@blurdybloop.com", // list of receivers
    subject: "Hello ✔", // Subject line
    text: "Hello world ✔", // plaintext body
    html: "<b>Hello world ✔</b>" // html body
}

// send mail with defined transport object
smtpTransport.sendMail(mailOptions, function(error, response){
    if(error){
        console.log(error);
    }else{
        console.log("Message sent: " + response.message);
    }

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

I just changed the user and pass in auth to my gmail account info (also tried with their values), and I changed the "to" email address to my email address. I get:

{ [Error: connect ECONNREFUSED]
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect' }

What am I missing? I don't see anything in the documentation that says I need to do anything more than this, so why won't it work? Thank you in advance.


Source: (StackOverflow)

Nodemailer/Gmail - What exactly is a refresh token and how do I get one?

I'm trying to do a simple contact form in a node app, using nodemailer. I want all the msg to be sent from a gmail account I made for this purpose, to my personnal mail.

on the client side, all I do is to get the name/mail/message of the customer and send it to the server. It works fine locally but fails to work when deployed (on heroku btw).

After a quick search, it seems I have to generate a ClientId and ClientSecret from Google Developers Console - which I did - but when it comes to generating a "refresh token" iI'm completely lost.

    var smtpTransport = nodemailer.createTransport("SMTP",{
        service:"Gmail",
        auth:{
            XOAuth2: {
                user:"myaccount@gmail.com",
                clientId:"",
                clientSecret:"",
                refreshToken:""
            }
        }
    });

I am confused : What exactly is a refresh token and how do I get one ?


Source: (StackOverflow)

What is the right way to set attachments path in nodeMailer?

I'am a newbie of Nodejs world. I want to send an email with embedded image. But my image didn't show in email. I thought it might be about my file path setting. Here is my mailOptions,

    var mailOptions = {
        from: 'mymail@gmail.com',
        to: to,
        subject: subject,
        html: html,
        attachments: [{
            filename: "logo.png",
            filePath: "/images/logo.png",
            cid: "logo-mail"
        }]
    };

And my directory that keeps my static files is

myproject/
         assets/
               images/
               js/
               styles/

And this is my html,

<img src="cid:logo-mail" />

Here is my result in an email,

<img src="cid.php?mid=e_ZGHjAQV4ZQLlAGNkZQNjZGN1AQt3Zt==&amp;pj=logo-mail" alt="cid.php?mid=e_ZGHjAQV4ZQLlAGNkZQNjZGN1AQ">

I am not sure that am I right to set file path like this ?

filePath: "/images/logo.png"

Source: (StackOverflow)

NodeJS NodeMailer username encoding

I'm using node mailer for sending a couple of emails with a custom smtp transporter & I would like to encode the username & password for my email server. Is there a way of doing it ?

var transport = nodemailer.createTransport(smtpTransport({
            host: 'smtp.example.com',
            port: 25,
            tls: {
                rejectUnauthorized: false
            },
            auth: {
                user: 'no-reply@example.com',
                pass: 'example'
            }
        }))

I would like to have something like this :

  auth: {
                user: 'bm9tcmVwbHk=',
                pass: 'QVRGGGF0QTE='
            }

Thanks !


Source: (StackOverflow)

NodeMailer Invalid Login

I am new to node.js programming .I am using nodemailer module for sending emails.

const nodemailer = require ('nodemailer'),
credentials=require('./credentials.js');
var mailTransport=nodemailer.createTransport({
    service:'Gmail',
    auth: {
        user : credentials.gmail.user,
        pass : credentials.gmail.password,
    }
});
function sendMail(mail_id){
    mailTransport.sendMail({
        from: ' "my name" <myname@gmail.com>',
        to : mail_id,   //user@gmail.com
        subject : 'Hello',
        text: "Hello How do u do ?",
    },function(err,info){
        if(err){
            console.log('Unable to send the mail :'+err.message);
        }
        else{
            console.log('Message response : '+info.response);
        }
    });
}
exports.sendMail=sendMail;

This is my program for sending emails to different users. But I am getting Invalid Login . I don't have any idea why this is coming . I am new to node.js and server side scripting.
I am using my gmail username and password for credentials.
Please help me.


Source: (StackOverflow)

Sending email via Node.js using nodemailer is not working

I've set up a basic NodeJS server (using the nodemailer module) locally (http://localhost:8080) just so that I can test whether the server can actually send out emails.

If I understand the SMTP option correctly (please correct me if I'm wrong), I can either try to send out an email from my server to someone's email account directly, or I can send the email, still using Node.js, but via an actual email account (in this case my personal Gmail account), i.e using SMTP. This option requires me to login into that acount remotely via NodeJS.

So in the server below I'm actually trying to use NodeJs to send an email from my personal email account to my personal email account.

Here's my simple server :

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);

However, it's not working. I got an email by Google saying :

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.

I couldn't find a solution for the above problem on the nodemailer GitHub page. Does anyone have a solution/suggestion ?

Thanks! :-)


Source: (StackOverflow)

SendGrid-nodejs or Nodemailer?

There are at least two ways to send email from Nodejs using SendGrid:

  1. Sendgrid provides a Nodejs library called "SendGrid-nodejs." They're actively supporting Sendgrid-Nodejs (last update 29 days ago).
  2. Nodemailer supports sendgrid and seems to be extremely popular. SendGrid posted an article about using this combination: Sending email with Nodemailer and Sendgrid.

Edit to make the question less opinion-based: What are the pros and cons to each approach? I have googled for days and not seen any comparison of the two. There is another StackOverflow question asking for differentiation between the two (among several other things) which has gone unanswered. So surely the answer to this will help others.

My specific usage, in case it helps focus the answers: I want to allow users of an iPhone app to invite others to use the app. They'll see the default invitation text in the app, and can customize it. The customized text is sent to my Nodejs server and added to a job queue. As the queue is processed, emails are sent. I want the emails to look nice, so I want to use HTML email templates (and a plaintext alternate body).

Scale-wise, this will start out very small but if the app is succssful could scale up rapidly.


Source: (StackOverflow)