Automatically Sending Notification Email w/ Server - javascript

I need to do a notification sender working on a linux server. The idea is once a week this sender do a query in JQL and, if it returns something, sends an email to a certain list.
I'm rather new to servers and javascript. I'm already doing the JQL query, but:
I need the Sender to know the right time to do it. What is the most efficient way to trigger the Sender?
How can I send an email in JS from an specific address to a list of emails?
A rough sketch:
//magic, part 1
WaitUntilMonday();
var result = DoJQLQuery();
if (result != '')
SendNotificationEmail(from,to,message);
//magic, part 2
I tried to search about it, but I don´t know where to start. I´d appreciate any suggest of reading material too. Thank you.

Well you can use NODEJS with sendgrid api for your server end and email api. The actual clientside, you could hook it up to a on a website or simply just run the nodejs application.
So the place to start would be https://nodejs.org/ and http://sendgrid.com
That would definitely handle your emailing needs. Here is a function I used stripped of my api key (obviously), the call to postEmail actually sends the mail, the rest is verification.
to send email its pretty easy. Good luck.
const SENDGRID_API_KEY = "SG.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var helper = require('sendgrid').mail;
var sg = require('sendgrid')(SENDGRID_API_KEY);
var emptyRequest = require('sendgrid-rest').request;
var request = require("request");
function makeEmail(whereFrom, whereTo, mysubject, mycontent){
from_email = new helper.Email(whereFrom);
to_email = new helper.Email(whereTo);
subject = mysubject;
content = new helper.Content("text/html", mycontent);
mail = new helper.Mail(from_email, subject, to_email, content);
custom_arg = new helper.CustomArgs("OURGUID", "ourcustomarg");
mail.addCustomArg(custom_arg);
var finished = mail.toJSON();
var timer = 0;
function postEmail(){
var requestBody = finished;
var requestPost = JSON.parse(JSON.stringify(emptyRequest));
requestPost.method = 'POST';
requestPost.path = '/v3/mail/send';
requestPost.body = requestBody;
sg.API(requestPost, function (error, response) {
console.log(response.statusCode + ' STATUS')
console.log('MESSAGE ID = '+ response.headers['x-message-id'])
if(response.statusCode == '202') {
console.log(response.statusCode + ' EMAIL SENT TO SENDGRID AND QUED')
}//response if statement
if(response.statusCode != '202'){
console.log(response.statusCode + ' Something went wrong')}
})//end internal api function
}//end api
postEmail(finished);//actually sending the mail
function getEmail(){
var requestBody = finished;
var requestPost = JSON.parse(JSON.stringify(emptyRequest));
requestPost.method = 'GET';
requestPost.path = '/v3/mail/send';
requestPost.body = requestBody;
sg.API(requestPost, function (error, response) {
console.log(response.statusCode + ' SUCCESSFUL EMAIL');
console.log('MESSAGE ID = '+ response.headers['x-message-id']) ;
})//end internal api function
}//end api
function checkBounce(){
console.log('this is checkBounce');
var options = { method: 'GET',
url: 'https://api.sendgrid.com/v3/suppression/bounces/'+ whereTo,
headers: { authorization: 'Bearer your api key here' },
body: '{}' };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(response.statusCode);
console.log(body);
});
}//check Bounce
function checkInvalid(){
console.log('This is check invalid');
var options = { method: 'GET',
url: 'https://api.sendgrid.com/v3/suppression/invalid_emails'+ whereTo,
headers: { authorization: 'Bearer your api key here' },
body: '{}' };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(response.statusCode);
console.log(body);
});
}//check Invalid
function checkBlock(){
console.log('This is check Block');
var options = { method: 'GET',
url: 'https://api.sendgrid.com/v3/suppression/blocks'+ whereTo,
headers: { authorization: 'Bearer your api key here' },
body: '{}' };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(response.statusCode);
console.log(body.created);
});
}//check Block
function checkTest(){
console.log('This is check Test');
var options = { method: 'GET',
url: 'https://api.sendgrid.com/v3/',
headers: { authorization: 'Bearer your api key here' },
body: '{}' };
request(options, function (error, response, body) {
if (error) throw new Error(error);
body = JSON.parse(body);
console.log(response.statusCode);
console.log(body);
});//end request
}//check Processed
}//make email end

Related

Header section has more than 10240 bytes (maybe it is not properly terminated)

I'm using NodeJs to try to upload an attachment to a Jira Issue via the Jira Rest API.
The api expects multipart/form-data so this is how I'm calling it in Node:
function uploadAttachments(supportFormData, callback) {
const url =
'https://somewhere.com/jira/rest/api/2/issue/' +
supportFormData.issueId +
'/attachments';
var options = {
url: url,
headers: {
Authorization: { user: username, password: password },
'X-Atlassian-Token': 'nocheck'
}
};
var r = request.post(options, function(err, res, body) {
if (err) {
console.error(err);
callback(false);
} else {
console.log('Upload successful! Server responded with:', body);
callback(false);
}
});
var form = r.form();
form.append('file', supportFormData.attachments[0].contents, {
filename: supportFormData.attachments[0].fileName,
contentType: supportFormData.attachments[0].contents
});
}
The error I'm receiving is:
org.apache.commons.fileupload.FileUploadException: Header section
has more than 10240 bytes (maybe it is not properly terminated)
The "supportFormData.attachments[0].contents" is ofType Buffer.
Any suggestions as to what could be causing this error?
I ran into this same issue and it turns out JIRA (or Java) requires \r\n as new line character. After I changed \n to \r\n my requests went through without problem.
If its a basic auth change options object to
let auth = new Buffer(`${username}:${password}`).toString('base64');
var options = {
url: url,
headers: {
Authorization: `Basic ${auth}`,
'X-Atlassian-Token': 'nocheck'
}
};

About node.js return data to ajax call function

Now I have a question like this:
I created a server with node.js ,and the server have receive a ajax request.With the data received from ajax ,node.js send a post request to another server. Now I have got the data from another server and the main question is how to send the data back to ajax, I have tried many ways but it does not work.
Can somebody help me on this issue?
here is my code
====ajax request
$.ajax({
type: "POST",
url: 'http://localhost:8888', // 这里要改成服务器的地址
data: userData,
success: function (data) {
console.log(data);
}
})
====
http.createServer(function (req, res) {
if (req.url == '/') {
var data = '';
var imdata;
util.log(util.inspect(req));
util.log('Request recieved: \nmethod: ' + req.method + '\nurl: ' + req.url);
req.on('data', function (chunk) {
imdata = querystring.parse(data += chunk);//转成对象的格式
})
req.on('end', function () {
var myIm = new ServerApi('e782429e48cb99f44b9c5effe414ac72', 'b88b9f2a2f74');
myIm.createUserId(imdata, function (err, data) {
//createUesrId is a api to deal with post request
console.log(data);//the data have received from another server,and now i do not know how to return the data to ajax success function
})
})
====the api to create user id with post requeset
ServerApi.prototype.postDataHttps = function (url, data, callback) {
this.checkSumBuilder();
var urlObj = urlParser.parse(url);
var httpHeader = {
'AppKey': this.AppKey,
'Nonce': this.Nonce,
'CurTime': this.CurTime,
'CheckSum': this.CheckSum,
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
'Content-Length': Buffer.byteLength(data)
};
var options = {
hostname: urlObj.hostname,
port: 80,
path: urlObj.path,
method: 'POST',
headers: httpHeader
};
var that = this;
var req = http.request(options, function (res) {
res.setEncoding('utf8');
console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);
res.on('data', function (chunk) {
if (Object.prototype.toString.call(callback) === '[object Function]') {
var result = JSON.parse(chunk);
callback.call(that, null, result);
return result;
}
});
});
var postData = querystring.stringify(data);
req.write(postData);
req.end(data);
req.on('error', function (err) {
if (Object.prototype.toString.call(callback) === '[object Function]') {
callback.call(that, err, null);
}
});
}
ServerApi.prototype.createUserId = function (data, callback) {
var url = 'https://api.netease.im/nimserver/user/create.action';
var postData = {
'accid': data['accid'] || '',
'name': data['name'] || '',
'props': data['props'] || '',
'icon': data['icon'] || '',
'token': data['token'] || ''
};
this.postDataHttps(url, postData, callback);
}
On your server code. The one with http.createServer(function (req, res) {...}
Notice how you got a req and res parameter?
So on event end, that is req.on('end' function... Right after the line where you got a comment saying the 'data is received from another server', you can do something like;
res.writeHead(/*HTTP_RESPONSE_CODE_FOR_AJAX_CLIENT=*/200);
res.end('Done');
to send a response back to your client with HTTP response code = 200 and the message in the HTTP body would be 'Done'. Note that, there are quite a number of things you can do with the response object, you may want to see the documentation for more information.
See:
https://nodejs.org/api/http.html#http_response_writehead_statuscode_statusmessage_headers
OR
(中文版)
http://nodeapi.ucdok.com/api/http.html#http_class_http_serverresponse_7847
Quick explanation in Chinese:
在服务器的代码req.on('end'...那里, 你可以用resobject打回给你的AJax client.

$.ajax call node js equivalent?

I am not very familiar with Node js and as well as dealing with http requests so pardon me if this is something obvious.
I am following the examples on this website:
$.ajax({
url: 'https://api.wit.ai/message',
data: {
'q': 'set an alarm in 10min',
'access_token' : 'MY_WIT_TOKEN'
},
dataType: 'jsonp',
method: 'GET',
success: function(response) {
console.log("success!", response);
}
});
I am trying to create the equivalent of this but in Node Js. I attempted to use 'node request' however my code is not working. I have attempted a lot of variations of this but to no avail.
Here is an example:
var request = require('request');
var url = 'https://api.wit.ai/message';
var data = {
'q': 'hello test123 trying to get entities from this message',
'access_token': 'MY_WIT_TOKEN'
};
request.get({ url: url, formData: data }, function (err, httpResponse, body) {
if (err) {
return console.error('post failed:', err);
}
console.log('Get successful! Server responded with:', body);
});
When I compile this code, my terminal replies with:
Something went wrong. We've been notified.
Use http:
var http = require('http');
http.get({
host: 'api.wit.ai',
path: '/message'
}, function(response) {
var body = '';
// get all data from the stream
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
// all data received
console.log(body)
});
});
To anyone interested here is the answer using node request that worked for me.
var request = require('request');
var headers = {
'Authorization': 'Bearer <WIT_TOKEN>'
};
var options = {
url: 'https://api.wit.ai/message?v=20160607&q=hello',
headers: headers
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
request(options, callback);

Arguments passed from request library are received but they aren't received when the arguments are sent from URL

I have a node.js server and I'm making GET requests.
The arguments passed using Python's requests and JavaScripts's request are received properly.
// Python
requests.get(url, data=data)
// JS
request.get({url: url, form:form}, function(){})
But the data is not received when I make the request from a browser like: url?a=1&b=2.
How do I fix it?
This is the function that I'm using to parse the form data:
function extractData(request, response, callback, options) {
var jsonString = '';
request.on('data', function(data) {
jsonString += data;
});
request.on('end', function() {
data = qs.parse(jsonString);
callback(request, response, data, options);
});
}
data is blank when I pass the arguments from URL.
I hope this will be helpful and below code is working to me
var options = {
host: 'services.com',
path: '/app/server.js/index/',
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Content-Length': data.length
}
};
var req = https.request(options, function(res) {
var msg = '';
res.setEncoding('utf8');
res.on('data', function(chunk) {
msg += chunk;//'chunk' response from server
if(chunk != "available")
{
var mail = {
from: "abc#gmail.com",
to: "ddd#gmail.com",
subject: "Alert! from production server",
html: "<p>Hi Team,</p> <p>Alert! production server is down.</p><p>Thanks,<br/>Maintenance Team</p>"
};
transporter.sendMail(mail, function(error, response){
if(error){
console.log(error);
//res.send({ "result" : "failure" });
}else{
console.log("Message sent: " + response);
//res.send({ "result" : "success" });
}
});
}
});
res.on('end', function() {
//console.log(JSON.parse(msg));
console.log(msg);
});

node.js variables from a module

I cannot figure out how to get a variable from a node.js module. I'm creating a module that will interface with an authentication mechanism, and currently it only returns a token. I need this token in the main.js, as I will be calling other modules, and passing this token for authentication.
//auth.js
var request = require("request");
var authModule = {};
var authToken = "";
var options = {
method: 'POST',
url: 'https://dummy.url/oauth/token',
headers: {
'authorization': 'Basic secretkeystring',
'accept': 'application/json',
'content-type': 'application/x-www-form-urlencoded'
},
form: {
grant_type: 'password',
username: 'indegomontoya',
password: 'sixfingeredman'
}
};
authModule.getToken = function getToken(){
request(options, requestToken);
};
function requestToken (error, response, body) {
if (error) throw new Error(error);
authToken = response.body.toString().split('\n')[1].split(":")[1].split('"')[1];
console.log("auth.js says: " + authToken);
// ^^ this works, and spits out the correct token to the console
return authToken;
};
module.exports = authModule;
module.exports.token = authToken;
And here is my main.js:
//main.js
var auth = require("./auth.js");
var token;
token = auth.getToken();
console.log("main.js says :"+ token);
// ^^ comes back undefined
I've seen examples of sending a variable from main.js to module.js, but I need to do the opposite. Any help is greatly appreciated!
EDIT: typo in code.
Try passing a hash instead.
module.exports = {
module: authModule,
token: authToken
}
var gcdm = require("./gcdm.js");
gcdm.module();
gcdm.token;
It appears that the request module (from here), is asynchronous in nature, meaning that it can take any length of time to return its data. This means that you may need to use a callback when using the getToken method.
Currently, your main.js app does not give suffiecient time for the auth.js module to fetch the token data. It requests the token and then in the same breath (or tick of the processor) it tries to print it to the console. To get around this problem, you need to utilise callbacks.
I would probably adjust your two auth module methods like so:
authModule.getToken = function getToken(callback){
request(options, function(error, response, body){
if (error) throw new Error(error);
callback( requestToken(body) );
});
};
function requestToken (body) {
authToken = response.body.toString().split('\n')[1].split(":")[1].split('"')[1];
return authToken;
};
Also, remove this uneeded line, as your callback will be the delivery mechanism back to your main app:
module.exports.token = authToken; // remove this
You would then use something like this to get the token in your main app:
gcdm.getToken( function (token) {
console.log('main.js says :' + token);
});
You may want to look a bit more into Asynchronous Programming in JavaScript. It's a key ingredient in the NodeJS toolbox.
#shennan thank you very much! You were right on track, and you are correct, request is async. I'm fairly new to node.js, so thanks for bearing with me, and am still trying to wrap my head around callbacks. (thanks #Drazisil for your link to callbackhell.com)
Your answers got me int he right direction, and I ended up with this:
//auth.js
var request = require("request");
var authModule = function () {};
var authToken = "";
var options = {
method: 'POST',
url: 'https://dummy.url/oauth/token',
headers: {
'authorization': 'Basic secretkeystring',
'accept': 'application/json',
'content-type': 'application/x-www-form-urlencoded'
},
form: {
grant_type: 'password',
username: 'indegomontoya',
password: 'sixfingeredman'
}
};
authModule.getToken = function getToken(callback){
request(options, function(error, response, body){
if (error) throw new Error(error);
authToken = response.body;
callback( requestToken(body) );
});
};
function requestToken (body) {
return authToken;
};
module.exports = authModule;
And:
//main.js
var auth = require("./auth.js");
var authTokenData;
function parseAuthJson(data) {
var jsonData = JSON.parse(data);
return jsonData;
}
auth.getToken( function (authTokenData) {
var jsonData = parseAuthJson(authTokenData);
console.log(jsonData.access_token);
});
I gathered help about parsing the JSON here.
Thanks for your help!

Categories