Nodejs sending email doesnt work from iphone browser - iphone

I am using the nodemailer module here: https://github.com/andris9/Nodemailer in order to send an email automatically from a webapp. Having tested it with a PC browser using firefox, everything seems to work fine. However, when I am using an iphone safari to use the app it does not seem to send the email. Ive been scratching my head forever on this and I would be very grateful if anyone knew what was the reason for this!! Note I am using the gmail service, but I have set my gmail so that it sends the message as another address (in this case xyz#abc.com). My code is as follows below:
emailer module:
var nodemailer = require("nodemailer");
function sendEmail(firstname, email){
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
auth: {
user: "user#gmail.com",
pass: "mypassword"
}
});
smtpTransport.sendMail({
from: "Sender <xyz#abc.com>",
to: email,
subject: "blahblah",
text: "blah blah blah",
}, function(error, response){
if(error){
console.log(error);
} else{
console.log("Success!");
}
});
}
exports.sendEmail = sendEmail;
app module:
var express = require("express");
var fs = require("fs");
var clientEmail = require("./clientEmail.js");
var profileEmail = require("./profileEmail.js");
var app = express();
app.use('/css', express.static(__dirname + '/css'));
app.use('/img', express.static(__dirname + '/img'));
app.use('/javascript', express.static(__dirname + '/javascript'));
app.use(express.bodyParser());
var buf = fs.readFileSync("html/index.html");
var index = buf.toString();
app.get('/', function(request, response) {
response.send(index);
});
app.post('/', function(request, response){
var email = request.body.email;
var name = request.body.name;
var firstname = request.body.firstname;
clientEmail.sendEmail(firstname,email);
response.redirect('/');
});
var port = process.env.PORT || 5000;
app.listen(port, function() {
console.log("Listening on " + port);
});

I have solved the issue. It was unrelated to nodemailer, I was actually using the toSource() function in my javascript which is not safari compatible. thanks all for your help

Related

Getting "TypeError: db.createList is not a function"

I am currently doing a React, Express, Massivejs, postgreSql app. I am getting the error "TypeError: db.createList is not a function" anytime I'm trying to hit my post endpoint. I'm not sure how to remedy it since it looks correct.
My file structure:
My server file looks like this:
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var massive = require("massive");
var connectionString = 'postgress://LonnieMcGill#localhost/todo';
var massiveInstance = massive.connectSync({connectionString : connectionString})
var config = require('./config.js');
var app = module.exports = express();
app.set('db', massiveInstance);
var listCtrl = require('./controller/listCtrl.js');
// **************** Middleware ****************
app.use(express.static(__dirname + './../public'));
app.use(bodyParser.json());
// ****************** Endpoints ***************
app.post('/api/add/list', listCtrl.createList);
app.get('/api/get/list', listCtrl.createList);
app.get('*', function(req, res) {
res.sendFile('index.html', { root: './public'});
})
app.listen(config.port, function() { console.log('Server initiated on port', config.port); });
My controller looks like this:
var app = require('../server.js');
var db = app.get('db');
module.exports = {
createList: function(req, res, next) {
console.log('db'my);
db.createList([req.body.name], function(err, res) {
res.status(200).send('List created');
})
},
readList: function(req, res) {
db.readList(function(err, res) {
if (err) {
console.log("readList failed");
} else {
console.log("readList working " + req.body, req.params);
}
})
}
}
My createList.sql file looks like this:
INSERT INTO list (
name
)
VALUES (
$1
);
The documentation clarifies this issue. By default, the "db" folder should stay in the root directory of your project, and not where the scripts consuming the database are (in this case, "server/").
You must either move "db" to the root directory of your project (so as to be alongside "server", "public", etc.), or configure the scripts property to point to that location:
var massiveInstance = massive.connectSync({
scripts: "server/db",
connectionString
})

Getting and "Error, wrong validation token" when trying to create a Facebook Chatbot

I'm trying to create a Facebook chatbot with NodeJS, Express, and a Heroku server.
I created my webhook on heroku and had it verified and saved by facebook. I then started adding code that would reply to the incoming messages and I can't seem to get it connected. It keeps saying "Error, wrong validation token" when I try to load my webhook in my browser. And when I try to send my bot a message I get no response. Even though I already had it verified and didn't change the code.
Here is my code:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var port = process.env.PORT || 3000;
// body parser middleware
app.use(bodyParser.urlencoded({ extended: true }));
// test route
//app.get('/', function (req, res) { res.status(200).send('Hello world!') });
app.get('/', function (req, res) {
if (req.query['hub.verify_token'] === '8FKU9XWeSjnZN4ae') {
res.send(req.query['hub.challenge']);
}
res.send('Error, wrong validation token');
})
app.post('/', function (req, res) {
messaging_events = req.body.entry[0].messaging;
for (i = 0; i < messaging_events.length; i++) {
event = req.body.entry[0].messaging[i];
sender = event.sender.id;
if (event.message && event.message.text) {
text = event.message.text;
sendTextMessage(sender, "Text received, echo: "+ text.substring(0, 200));
}
}
res.sendStatus(200);
});
// error handler
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(400).send(err.message);
});
app.listen(port, function () {
console.log('Listening on port ' + port);
});
var token = <myToken>;
function sendTextMessage(sender, text) {
messageData = {
text:text
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
});
}
So I'm confused as to why nothing is happening and why I'm getting that error. I feel like I'm missing a whole step. I am following this tutorial by the way: https://developers.facebook.com/docs/messenger-platform/quickstart
Any help is appreciated. Thanks!
Edit: Here are my heroku logs
Do not post your full access tokens here!
Have you tested the output of the challenge? Since it's just a GET and you know all values you can try it yourself: your-app-domain.com/your-callback-url?hub_mode=subscribe&hub_verify_token=the_token_you_set_in_your_app_config&hub_challenge=ping which sould print 'ping' if everything work fine.
Make sure you add sendStatus(200) to the hub challenge response, too.
You need to subscribe your page to the app first. To do so make a POST request to /your-page-id/subscribed_apps which should return "success". You can make a GET request to the same endpoint afterwards to double check your app is subscribed to your page
You did not mention which events you subscribed to (needs to be message_deliveries, messages, messaging_optins, messaging_postbacks)
Make sure the webhooks tab in your app dashboard now says "complete"
Test again
You are actually using "request" but you are never importing it anywhere. Here's how to fix it:
var request = require("request")
Once you have added that to your index.js or app.js file (basically whatever this file is), make sure you do:
npm install request --save
This should fix it. Unfortunately, Heroku doesn't error out and say that it does not know what "request" is and that's why it was so hard to figure this out in the first place!

Getting error sending email in nodejs with emailjs

[error: can't set headers after they are sent.]
createCredentials() is deprecated, use tls.createSecureContext instead
{[Error: bad response on command '-']
code:2
smtp : '550 5.3.4 Requested action not token; To continue sending messages,
please sign in to your account.\n}
I have been trying to send email in nodejs with emailjs and nodemailer but i keep on getting the error above.
transportEmail: email.server.connect({
user: "ghConnectUs#outlook.com",
password:"******",
host: "smtp-mail.outlook.com",
tls: {ciphers: "SSLv3"}
})
note: i have include all modules.
i'm hoping somebody can point me to the right path. i just want to send me using outlook or gmail in node app.
Below is the code for sending email from nodejs app (through Gmail):
Using Nodemailer v1.3.4:
var nodemailer = require("nodemailer");
var transporter = nodemailer.createTransport({
service: "Gmail",
auth: {
user: "email_id_of_gmail_account",
pass: "password_of_gmail_account"
}
});
var mailOptions = {
from: 'sender_email_id', // sender address
to: 'receiver_email_id, some_other_email_if_requierd', // list of receivers
cc: 'cc_email_id'
subject: 'subject text', // Subject line
text: 'body plain text', // plaintext body
html: '<b>body html</b>' // html body
};
var sendEMail = function () {
transporter.sendMail(mailOptions, function(error, info){
if(error){
console.log(error);
}else{
console.log('Message sent: ' + info.response);
}
});
};
sendEmail();
Note: if you are using Nodemailer version 0.7 or lower, then transporter object will created like this:
var transporter = nodemailer.createTransport('SMTP', {
service: "Gmail",
auth: {
user: "email_id_of_gmail_account",
pass: "password_of_gmail_account"
}
});
Using emailJs v0.3.16:
var email = require("/node_modules/emailjs/email.js");
var server = email.server.connect({
user: "emailId_of_gmail_account",
password: "password_of_gmail_account",
host: "smtp.gmail.com",
ssl: true // in case outlook, use "tls: {ciphers: "SSLv3"}"
});
var message = {
text: "body text",
from: "senderName <sender's_email_id>",
to: "receiverName <receiver_email_id>",
subject: "subject text",
attachment: // optional
[
{data: "<html>i <i>hope</i> this works! html </html>", alternative: true},
{path: "path/to/file.zip", type:"application/zip", name:"renamed.zip"}
]
};
var sendEMail = function () {
server.send(message, function (err, message) {
console.log(err || message);
});
};
sendEmail();

Use socket.io with HTTPS instead of HTTP

I am using self-signed certificated to encrypt traffic data.
My .crt and .key files are located at /etc/nginx/ssl/
(some_file.key and some_file.crt)
I was using socket.io over http but tried to get it over to https. Here is my actual code:
var formidable = require('formidable');
var express = require('express');
var fs = require('fs');
var privateKey = fs.readFileSync('../etc/nginx/ssl/some_file.key').toString();
var certificate = fs.readFileSync('../etc/nginx/ssl/some_file.crt').toString();
//how can I exclude this? (I have no intermediate, should I?)
var ca = fs.readFileSync('../intermediate.crt').toString();
var app = express.createServer({key:privateKey,cert:certificate,ca:ca });
var io = require('socket.io');
app.listen(3000, function(){
//wait on 3000
});
app.post('/posts', function(req, res){
//server communication
});
io.on('connection', function(socket){
//wait on connections
});
Client-side:
var socket = io(url + ":3000", { "secure": true, 'connect timeout': 5000 });
Is this the correct way to do it? I based my https code on examples, so I'm doubting on whether this is well enough (I know it isn't, but should be close). When I run the code, I also get an error no such file or directory '../etc/nginx/ssl/some_file.key'...
I use it this way, although this is very dependent on express version you are using. This is for version 3.4
var express = require('express')
, app = express()
,fs = require('fs')
,events = require('events');
...
var options = {
key: fs.readFileSync('/etc/nginx/ssl/some_file.key'),
cert: fs.readFileSync('/etc/nginx/ssl/some_file.crt')
};
/*
*Configuration
*
*/
var server = require('https').createServer(options, app), io = require("socket.io").listen(server);
var port = 8443;
var ipaddr = '0.0.0.0';
app.configure(function() {
app.set('port', port);
app.set('ipaddr', ipaddr);
app.use(express.bodyParser());
app.use(express.methodOverride());
...
});

Blog created with ExpressJS backed by MongoDB not showing posts from DB

I've created a very simple blog web app with ExpressJS and MongoDB. But the index page doesn't render the 'blogPosts' that I input into the DB. It only shows the title as "BL's Blog", without any posts below.
Why aren't the posts showing?
app.js:
//Module dependencies
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
//Mongodb
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/hello-express/');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
//GET
app.get('/', routes.index(db));
app.get('/users', user.list);
app.get('/userlist', routes.userlist(db));
app.get('/newuser', routes.newuser);
//POST
app.post('/adduser', routes.adduser(db));
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
routes/index.js(I only included exports.index as it's the relevant route to this problem):
exports.index = function(db) {
return function(req, res) {
var posts = db.get('blogPosts');
posts.find({}, {}, function(e, docs) {
res.render('index', {
"index": docs
});
});
};
};
views/index.jade:
extends layout
block content
h1.
BL's Blog
ul
- each post in index
li
h3 = post.title
p = post.content
Ok now I have actually found out the answer to my own question, thanks to the help of WiredPrairie.
The first problem lies with the name of the database that I'm using. Thus in my index.js, it should have been:
exports.index = function(db) {
return function(req, res) {
var posts = db.get('hello-express'); //Here's the difference.
posts.find({}, {}, function(e, docs) {
res.render('index', {
"index": docs
});
});
};
};
I listed in app.js that I'm using the database called 'hello-express' with this line below:
var db = monk('localhost:27017/hello-express/');
Hence the name of database being used should be named as 'hello-express'.
However, even after doing so, I could not render the Jade page properly. This was due to a syntax error (I know, I'm new.)
extends layout
block content
h1.
BL's Blog
ul
- each post in index
li
h3 #{post.title}
p #{post.content}
By using #{<var>} instead of =, the page was able to render properly. I still have no idea why this is the case, but at least it has solved my problem for now.