Not able to send mail from heroku using nodemailer - javascript

This is the error I get on heroku when I am trying to send emails from my deployed application.
{ Error: Connection timeout
2018-07-28T21:37:39.586059+00:00 app[web.1]: at SMTPConnection._formatError (/app/node_modules/nodemailer/lib/smtp-connection/index.js:606:19)
2018-07-28T21:37:39.586061+00:00 app[web.1]: at SMTPConnection._onError (/app/node_modules/nodemailer/lib/smtp-connection/index.js:579:20)
2018-07-28T21:37:39.586063+00:00 app[web.1]: at Timeout._connectionTimeout.setTimeout (/app/node_modules/nodemailer/lib/smtp-connection/index.js:261:18)
2018-07-28T21:37:39.586066+00:00 app[web.1]: at ontimeout (timers.js:365:14)
2018-07-28T21:37:39.586067+00:00 app[web.1]: at tryOnTimeout (timers.js:237:5)
2018-07-28T21:37:39.586069+00:00 app[web.1]: at Timer.listOnTimeout (timers.js:207:5) code: 'ETIMEDOUT', command: 'CONN' }
I am using nodemailer version 4.6.7 and here's the code:
'use strict';
const nodemailer = require('nodemailer');
module.exports = {
sendMail: function(email) {
console.log(email)
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport(sails.config.connections.mailer);
// setup email data with unicode symbols
let mailOptions = {
from: '"Medico 👻" <test#testgmail.com>', // sender address
to: email, // list of receivers
subject: 'Test', // Subject line
text: 'Hello world?', // plain text body
html: 'Hello world?' // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: %s', info.messageId);
// Preview only available when sending through an Ethereal account
console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
});
}
}
I am using the generated app password from google and that works perfectly fine when I run it locally but on heroku it is throwing error.
What am I doing wrong?

Related

NodeMailer error when sending email. On production only

I'm using the following code to create a SMTPtransporter that will be used to send emails. The code works perfectly fine on my computer. With Yarn version '1.22.17'.
import * as nodemailer from 'nodemailer';
import * as SMTPTransport from "nodemailer/lib/smtp-transport";
const poolOptions = {
pool: true,
maxConnections: 1,
maxMessages: 5
}
const smtpOptions = {
host: 'smtp.gmail.com',
port: 587,
secure: false,
auth: {
user: SMTP_USER,
pass: SMTP_PASSWORD
},
tls:{
ciphers: 'SSLv3',
rejectUnauthorized: false
}
}
const nodemailerOptions: SMTPTransport.Options = {
...poolOptions,
...smtpOptions
}
const transport = nodemailer.createTransport(nodemailerOptions);
The send email function :
export function sendMail(
to: string, subject: string, text: string, html: string) {
const mailOptions = {
from: 'Bobo <no-reply#bobo.bo>', to, subject, text, html
};
return new Promise((resolve, reject) => {
transport.sendMail(mailOptions, (error, info) => {
if (error) {
console.error(
`Failed to send email to ${to} with body [${text}]`, error);
reject(new Error('Email sending failed'));
} else {
console.log(
`Email sent to ${to} with subject [${subject}]`, info.response);
resolve();
}
});
});
}
Meanwhile in the server i got the following error each time i try to send an email :
{ Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:111:27)
errno: 'ECONNRESET',
code: 'ECONNECTION',
syscall: 'read',
command: 'CONN' }
It's the same app deployed in ubuntu server with same Yarn version.
If anyone can help i would be very grateful.
NOTE :: For the deployment on the server, i used Nginx to forward all the requests on port 80 to 3000 (App running). And the ports for SMTP are open (25,587)
It seems to be some kind of problem related to the TLS node library, there is an already question addressing this problem, you can find it here
The problem was due to the restriction in the network put by the hosting company. I adjusted the smtp host to one they allow trafic with.

Why Can't I connect SQL Server to my node js

I'm using the 'mssql' npm package to connect my SQL server to my node JS.
I went through a few questions, but it wasn't solved anywhere.
My SQL Server login credentials are-
server type : Database Engine
Server name : DESKTOP-MPF88ST\KUSHAL
authentication : sql server authentication
login : username
password : password
and the database I wanna get is schoolDB
and my code goes something like this
const sql =require("mssql")
const config = {
login: 'username',
password:'password',
server: 'localhost',
database: "schoolDB",
options : {
enableArithAbort: true
},
port : 1433
}
sql.connect(config, (err) => {
if(err){
console.log(err);
}
else {
console.log("Connected")
}
I have my TCP/IP enabled and set up, SQL Server Browser enabled, but it still throws the error-
ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at Connection.<anonymous> (E:\Kushals\server\node_modules\mssql\lib\tedious\connection-pool.js:68:17)
at Object.onceWrapper (events.js:422:26)
at Connection.emit (events.js:315:20)
at Connection.socketError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connection.js:1290:12)
at E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connection.js:1116:21
at SequentialConnectionStrategy.connect (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connector.js:87:14)
at Socket.onError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connector.js:100:12)
at Socket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3) {
code: 'ESOCKET',
originalError: ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at ConnectionError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\errors.js:13:12)
at Connection.socketError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connection.js:1290:56)
at E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connection.js:1116:21
at SequentialConnectionStrategy.connect (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connector.js:87:14)
at Socket.onError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connector.js:100:12)
at Socket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: 'ESOCKET'
}
}
How can I solve it ??
Try this:
const sql = require('mssql/msnodesqlv8')
const pool = new sql.ConnectionPool({
login: 'username',
password:'password',
database: 'schoolDB',
server: 'DESKTOP-MPF88ST\KUSHAL',
driver: 'msnodesqlv8',
options: {
trustedConnection: true
}
})
pool.connect().then(() => {
//sample query
pool.request().query('select 1 as number', (err, result) => {
console.dir(result)
})
})
Ensure that the TCP/IP protocol is Enabled as it is disabled by default.
Steps:
Go to Computer management
Under Service and Applications -> SQL Server Configuration Manager
-> SQL Server Network configuration -> click on "Protocols for MSSQLSERVER"
You will see TCP/IP section (to enable right click and enable it)

Requesting tables from MS Sql - Node.js web service

I am in need of assistance in terms of generating a request to my Microsoft SQL Server via a web service (Built in Node.js).
To summarize the problem at hand, it is as follows: I am currently logging into a MS Sql Server Management with a windows auth account - that is all find and dandy however, I am now trying to build a web service that allows for selects and transacts of some tables which is where I am running into issues now specifically in terms of logging in and pulling data to the web service.
Code
var express = require('express'); var app = express();
app.get('/',function(req,res) {
const sql = require('mssql');
// Connection Path
const myServerPath = String("xxxx\\WS1SQLEXPRESS");
// Connection String Parameter
const config = {
// User Login Details - Windows Auth or General User Account
user : 'xxxx-xxx\\AdrianH',
password: 'xxxxxx',
// Server path to connect to
server : myServerPath,
// Database
datebase: 'plex',
options : {
trustedConnection: true
}
};
sql.connect(config,function(err) {
if (err) console.log(err);
// Create Request Object
var request = new sql.Request();
// Query the Database
request.query('USE plex; SELECT * FROM [plex].[dbo].[tblWorkCenters]',function(err,recordset) {
if (err) console.log(err)
// send records as response
res.send(recordset);
});
});
});
// Start Server and listen on //http://localhost:8001/
var server = app.listen(3213,function(){
console.log('Server is running...');
});
I have hid sensitive information, here is the error code
{ ConnectionError: Login failed for user ''.
at Connection.tedious.once.err (C:\Users\adrianh\node_modules\mssql\lib\tedious.js:244:17)
at Object.onceWrapper (events.js:286:20)
at Connection.emit (events.js:198:13)
at Connection.processLogin7Response (C:\Users\adrianh\node_modules\tedious\lib\connection.js:1397:14)
at Connection.message (C:\Users\adrianh\node_modules\tedious\lib\connection.js:1932:14)
at Connection.dispatchEvent (C:\Users\adrianh\node_modules\tedious\lib\connection.js:1084:36)
at MessageIO.messageIo.on (C:\Users\adrianh\node_modules\tedious\lib\connection.js:984:14)
at MessageIO.emit (events.js:198:13)
at Message.message.on (C:\Users\adrianh\node_modules\tedious\lib\message-io.js:32:14)
at Message.emit (events.js:203:15)
code: 'ELOGIN',
originalError:
{ ConnectionError: Login failed for user ''.
at ConnectionError (C:\Users\adrianh\node_modules\tedious\lib\errors.js:13:12)
at Parser.tokenStreamParser.on.token (C:\Users\adrianh\node_modules\tedious\lib\connection.js:735:29)
at Parser.emit (events.js:198:13)
at Parser.parser.on.token (C:\Users\adrianh\node_modules\tedious\lib\token\token-stream-parser.js:27:14)
at Parser.emit (events.js:198:13)
at addChunk (C:\Users\adrianh\node_modules\readable-stream\lib\_stream_readable.js:297:12)
at readableAddChunk (C:\Users\adrianh\node_modules\readable-stream\lib\_stream_readable.js:279:11)
at Parser.Readable.push (C:\Users\adrianh\node_modules\readable-stream\lib\_stream_readable.js:240:10)
at Parser.Transform.push (C:\Users\adrianh\node_modules\readable-stream\lib\_stream_transform.js:139:32)
at doneParsing (C:\Users\adrianh\node_modules\tedious\lib\token\stream-parser.js:80:14) message: 'Login failed for user \'\'.', code: 'ELOGIN' },
name: 'ConnectionError' }
{ ConnectionError: Connection is closed.
at Request._query (C:\Users\adrianh\node_modules\mssql\lib\base.js:1399:37)
at Request._query (C:\Users\adrianh\node_modules\mssql\lib\tedious.js:546:11)
at Request.query (C:\Users\adrianh\node_modules\mssql\lib\base.js:1335:12)
at C:\Users\adrianh\Desktop\JEC_Current_Projects\WebService\WCWebServiceIOS.js:30:13
at _poolCreate.then.catch.err (C:\Users\adrianh\node_modules\mssql\lib\base.js:287:7)
at process._tickCallback (internal/process/next_tick.js:68:7) code: 'ECONNCLOSED', name: 'ConnectionError' }
** An interesting note to make is in --
(C:\Users\adrianh\node_modules\tedious\lib\token\stream-parser.js:80:14) message: 'Login failed for user \'\'.', code: 'ELOGIN' },
name: 'ConnectionError' }
It doesn't actually seem to pass my login information - any help will be greatly appreciated thank you.
If you are trying to connect mssql via windows authentication in node JS use this module.
var mssql = require('mssql/msnodesqlv8
Sample:
var mssql = require('mssql/msnodesqlv8')
var dbConfig = {
server: 'server',
driver: 'msnodesqlv8',
database: 'DBDATA',
port: '1433',
options: {
trustedConnection: true,
debug: {
packet: false,
payload: false,
token: false,
data: false
},
}
};

Session.send() does not work: "session is not defined"

I am trying to use session.send instead of console.log in transporter.sendMail, so that the user knows when the Email was sent successfully, but it does not work.
The error is "session is not defined".
This is how my code looks like:
var nodemailer = require('nodemailer');
// Create the transporter with the required configuration for Gmail
// change the user and pass !
var transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true, // use SSL
auth: {
user: 'myemail#gmail.com',
pass: 'myPassword'
}
});
// setup e-mail data
var mailOptions = {
from: '"Our Code World " <myemail#gmail.com>', // sender address (who sends)
to: 'mymail#mail.com, mymail2#mail.com', // list of receivers (who receives)
subject: 'Hello', // Subject line
text: 'Hello world ', // plaintext body
html: '<b>Hello world </b><br> This is the first email sent with Nodemailer in Node.js' // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info,session){
if(error){
return console.log(error);
}
session.send('Message sent: ' + info.response);
}
);
this is an example of how to doing it. Just make sure you call this method inside a session context like:
const sendmail = require('./email'); // in case you have the class called email
bot.dialog('/', function(session) {
sendmail.sendmail(session);
session.send("hello")
});
function sendmail(session){
var nodemailer = require('nodemailer');
// Create the transporter with the required configuration for Outlook
// change the user and pass !
var transport = nodemailer.createTransport( {
service: "hotmail",
auth: {
user: "",
pass: ""
}
});
// setup e-mail data, even with unicode symbols
var mailOptions = {
from: '"Our Code World " <shindar902009#hotmail.com>', // sender address (who sends)
to: 'shindar902009#hotmail.com', // list of receivers (who receives)
subject: 'Hello ', // Subject line
text: 'Hello world ', // plaintext body
html: '<b>Hello world </b><br> This is the first email sent with Nodemailer in Node.js' // html body
};
// send mail with defined transport object
transport.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
session.send('Message sent');
});
}
module.exports.sendmail = sendmail;
transporter.sendMail(mailOptions, function(error, info , session)
You are not using a correct function definition, since the callback of transport.SendMail can only have two parameters (error & info). Have a look at the Nodemailer example.
In your case it would look like this. Just make sure you use this snippet where the session context is available.
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return session.error(error);
}
session.send('Message sent: ' + info.messageId);
});
I just ran this snippet replacing the username and password appropriately and ended up with this:
{ Error: Invalid login: 534-5.7.14 <https://accounts.google.com/signin/continu> Please log in via
534-5.7.14 your web browser and then try again.
534-5.7.14 Learn more at
534 5.7.14 https://support.google.com/mail/answer/ - gsmtp
at SMTPConnection._formatError (C:\projects\nodemailertest\node_modules\nodemailer\lib\smtp-connection\index.js:605:19)
at SMTPConnection._actionAUTHComplete (C:\projects\nodemailertest\node_modules\nodemailer\lib\smtp-connection\index.js:1340:34)
at SMTPConnection._responseActions.push.str (C:\projects\nodemailertest\node_modules\nodemailer\lib\smtp-connection\index.js:378:26)
at SMTPConnection._processResponse (C:\projects\nodemailertest\node_modules\nodemailer\lib\smtp-connection\index.js:764:20)
at SMTPConnection._onData (C:\projects\nodemailertest\node_modules\nodemailer\lib\smtp-connection\index.js:570:14)
at TLSSocket._socket.on.chunk (C:\projects\nodemailertest\node_modules\nodemailer\lib\smtp-connection\index.js:522:47)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at TLSSocket.Readable.push (_stream_readable.js:134:10)
code: 'EAUTH',
response: '534-5.7.14 <https://accounts.google.com/signin/continue?..._sniped> Please log in via\n534-5.7.14 your web browser and then try again.\n534-5.7.14 Learn more at\n534 5.7.14 https://support.google.com/mail/answer/78 - gsmtp',
responseCode: 534,
command: 'AUTH PLAIN' }
Furthermore I received an email from Google:
Someone just used your password to try to sign in to your account from a non-Google app. Google blocked them, but you should check what happened. Review your account activity to make sure no one else has access.
Are you sure this is the code that you're running? The error you posted, "session is not defined" seems like a syntax error.

Using nodemailer and smtp send mail without authentication

Below is my code. This works fine with gmail smtp server.
But when I use my office one (which does not require authentication) it fails
May be the syntax I am using is wrong.
below is the code working with gmail smtp:
var mailOptions = {
from: 'xxxx#abcd.com',
to: 'xxxxyy#abcd.com',
subject: 'hello world!',
html: '<img src="cid:logo">',
attachments: [{
filename: 'test.png',
path: 'D:/bbbbb/mmmm/src/test.png',
cid: 'logo' //same cid value as in the html img src
}]
};
transport.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
}
console.log(`Message sent: ${info.response}`);
});
As Our company smtp does not require authentication,
I have tried below code:
var transport = nodemailer.createTransport("smtps://xxxx#abcd.com:"+encodeURIComponent('') + "#xxxx.xxxrxx.com:25");
OR
var transport = nodemailer.createTransport("smtps://xxx.xxx.com:25");
but all resulted error
{ Error: 101057795:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:openssl\ssl\s23_clnt.c:797:
at Error (native) code: 'ECONNECTION', command: 'CONN' }
My guess is syntax is wrong.
Can some one pls correct me
Thanks and Regards.
You can remove auth option from the example code when creating an SMTP Transport message.
so it should look like the following:
/**
* Initialize transport object
*/
const transporter = nodemailer.createTransport({
host: "", //Host
port: , // Port
secure: true
});
let mailOptions = {
from: , // sender address
to: , // list of receivers
subject: , // Subject line
text: , // plain text body
html: // html body
};
/**
* send mail with defined transport object
*/
transporter.sendMail(mailOptions,
(error, info) => {
});

Categories