Remove all but the text written by user - node.js

I use Outlook API to fetch the sent email's body. Now, I want to clean the body to remove all links, headers, etc. and keep only the text written by user. Following is my regex function:
function getRegex() {
var regex1 = /^(?=.*Forwarded message)[^]*/m;
var regex2 = /^(?=.*From: )[^]*/m;
var regex3 = /^(?=.*On )[^]*/m;
var regex4 = /^(?=.*http)[^]*/m;
return new RegExp("(" + regex1.source + ")|(" + regex2.source + ")|(" + regex3.source + ")|(" + regex4.source + ")");
}
Following is function to fetch sent emails from Outlook:
outlook.mail.getMessages({
token: token.token.access_token,
odataParams: queryParams,
folderId: 'SentItems'
}, function (err, result) {
if (err){
console.log(err);
return;
}
var mail_array = result.value;
var outlook_sent_emails = '';
mail_array.forEach(function (mail) {
if (mail.BodyPreview !== '') {
outlook_sent_emails += (mail.BodyPreview + " ");
}
});
console.log(outlook_sent_emails.replace(getRegex(), "")); //This is not working
});
This line console.log(outlook_sent_emails.replace(getRegex(), "")); shows I am still getting all links, headers, etc.
The same regex is working elsewhere in my code.
EDITED:
Sample Text:
From: <Name>
Sent: <Datetime>
To: <Name>
Subj Dear Sir/Madam
Hi Vaibhav,
Hope you are doing well.
http://developer.android.com/sdk/index.html
Sent from my Windows 10 phone
I want to remove all kinds of links and text like as follows from the string:
From: <Name>
Sent: <Datetime>
To: <Name>
Subj Dear Sir/Madam
EXPECTED OUTPUT:
Hi Vaibhav,
Hope you are doing well.

UPDATE: added http
You may try this:
^.*(From:|Sent:|Sent\s+From|To:|Subj|Dear\s+(Sir|Madam)|http).*$
and replace by ""
Demo
const regex = /^.*(From:|Sent:|Sent\s+From|To:|Subj|Dear\s+(Sir|Madam)|http).*$/gmi;
const str = ` From: <Name>
Sent: <Datetime>
To: <Name>
Subj Dear Sir/Madam
Hi Vaibhav,
Hope you are doing well.
http://developer.android.com/sdk/index.html
Sent from my Windows 10 phone`;
const subst = ``;
const result = str.replace(regex, subst).trim();
console.log(result);

Related

Facing Error while sending email with Multiple Excel Attachments

I am trying to send 6 x Excel Sheets as Attachment from 1 Google Sheet as Attachment, sometimes this code run's perfectly but sometime it gives the error.
The Original Code
///*** SEND 6 X ATTACHMENTS IN 1 EMAIL FROM GOOGLE SHEET USING APP SCRIPT ***///
function sendExcelAttachmentsInOneEmail() {
var url = "https://docs.google.com/spreadsheets/d/"+SpreadsheetApp.getActiveSpreadsheet().getId()+"/export"+"?format=xlsx&"+"gid="+SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getSheetId();
var url1 = "https://docs.google.com/spreadsheets/d/"+SpreadsheetApp.getActiveSpreadsheet().getId()+"/export"+"?format=xlsx&"+"gid="+SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2").getSheetId();
var url2 = "https://docs.google.com/spreadsheets/d/"+SpreadsheetApp.getActiveSpreadsheet().getId()+"/export"+"?format=xlsx&"+"gid="+SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet3").getSheetId();
var url3 = "https://docs.google.com/spreadsheets/d/"+SpreadsheetApp.getActiveSpreadsheet().getId()+"/export"+"?format=xlsx&"+"gid="+SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet4").getSheetId();
var url4 = "https://docs.google.com/spreadsheets/d/"+SpreadsheetApp.getActiveSpreadsheet().getId()+"/export"+"?format=xlsx&"+"gid="+SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet5").getSheetId();
var url5 = "https://docs.google.com/spreadsheets/d/"+SpreadsheetApp.getActiveSpreadsheet().getId()+"/export"+"?format=xlsx&"+"gid="+SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet6").getSheetId();
var ss3 = SpreadsheetApp.getActiveSpreadsheet();
var sheet3 = ss3.getSheetByName("Sheet7");
var value4 = sheet3.getRange("J1").getValue();
var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
var blob = UrlFetchApp.fetch(url, params).getBlob().setName("Sheet1 XYZ Reports.xlsx");
var blob1 = UrlFetchApp.fetch(url1, params).getBlob().setName("Sheet2 TXT Data.xlsx");
var blob2 = UrlFetchApp.fetch(url2, params).getBlob().setName("Sheet3 RAW FILES.xlsx");
var blob3 = UrlFetchApp.fetch(url3, params).getBlob().setName("Sheet4 SYS DATA.xlsx");
var blob4 = UrlFetchApp.fetch(url4, params).getBlob().setName("Sheet5 REPORTED ISSUES.xlsx");
var blob5 = UrlFetchApp.fetch(url5, params).getBlob().setName("Sheet6 FIXED ISSUES.xlsx");
var message = {
to: "email#domain.com",
cc: "email#domain.com",
subject: "REPORTS - "+value4,
body: "Hi Team,\n\nPlease find attached Reprots.\n\nBest Regards!",
name: "",
attachments: [blob, blob1, blob2, blob3, blob4, blob5]
}
MailApp.sendEmail(message);
}
Error Message from App Script
9:05:45 PM Notice Execution started
9:05:49 PM Error Exception: Request failed for https://docs.google.com returned code 429. Truncated server response: <!DOCTYPE html><html lang="en"><head><meta name="description" content="Web word processing, presentations and spreadsheets"><meta name="viewport" c... (use muteHttpExceptions option to examine full response)
sendExcelAttachmentsInOneEmail # Code.gs:44
I have made it work and also did an overhaul to the script due to personal reasons (I don't like repetitive lines of code). See the working script below.
Script:
function sendExcelAttachmentsInOneEmail() {
var sheets = ['Sheet1', 'Sheet2', 'Sheet3', 'Sheet4', 'Sheet5', 'Sheet6'];
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var spreadSheetId = spreadSheet.getId();
var urls = sheets.map(sheet => {
var sheetId = spreadSheet.getSheetByName(sheet).getSheetId();
// Used this alternative url since I'm getting the error below. This other url has less traffic issues during testing:
// "This file might be unavailable right now due to heavy traffic. Try again."
return `https://docs.google.com/feeds/download/spreadsheets/Export?key=${spreadSheetId}&gid=${sheetId}&exportFormat=xlsx`;
});
var reportName = spreadSheet.getSheetByName('Sheet7').getRange(1, 10).getValue();
var params = {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
},
// Add mute http exceptions to proceed
muteHttpExceptions: true
};
var fileNames = ['Sheet1 XYZ Reports.xlsx',
'Sheet2 TXT Data.xlsx',
'Sheet3 RAW FILES.xlsx',
'Sheet4 SYS DATA.xlsx',
'Sheet5 REPORTED ISSUES.xlsx',
'Sheet6 FIXED ISSUES.xlsx'];
var blobs = urls.map((url, index) => {
// Added an interval due to heavy traffic error. Increase interval if needed.
Utilities.sleep(1000);
return UrlFetchApp.fetch(url, params).getBlob().setName(fileNames[index]);
});
var message = {
to: 'user#domain.com',
subject: 'REPORTS - ' + reportName,
body: "Hi Team,\n\nPlease find attached Reports.\n\nBest Regards!",
attachments: blobs
}
MailApp.sendEmail(message);
}
Output:
Notes:
Important bits here are the following:
muteHttpExceptions
The alternative url for less traffic issues
Utilities.sleep(1000)

Redirect back to the app Issue after paytm payment success in web using node js

Implemented paytm payment logic in nodejs. After successful payment it is not redirecting to success message simply it is showing "Redirect back to the page" in prod environment. Below is my code. Also attached screenshot. Please help me if i miss anything.enter image description here
app.post('/payment', urlencodedParser, (req,res)=>{
let reqbody = req.body;
let orderId = 'order_'+ Math.random().toString(36).substring(7);
let params = {}
params['MID'] = 'My Merchant Id',
params['WEBSITE'] = 'DEFAULT',
params['CHANNEL_ID'] = 'WEB',
params['INDUSTRY_TYPE_ID'] = 'Retail',
params['ORDER_ID'] = orderId,
params['CUST_ID'] = 'CUST' + Math.random().toString(36).substring(7),
params['TXN_AMOUNT'] = '1',//+reqbody.money+'',
params['CALLBACK_URL'] = 'https://securegw.paytm.in/theia/paytmCallback?ORDER_ID='+orderId+'',
params['EMAIL'] = 'myemail#gmail.com',
params['MOBILE_NO'] = '9999999999',
checksum_lib.genchecksum(params, '9KBKBVjiB3ml5TSP', function(err, checksum){
let txn_url = 'https://securegw.paytm.in/order/process';
let form_fields =''
for(x in params){
form_fields +="<input type='hidden' name = '"+x+"' value = '"+params[x]+"'/>"
}
form_fields +="<input type='hidden' name = 'CHECKSUMHASH' value = '"+checksum+"' />"
var html = '<html><body><center><h1>Please wait! Do not refresh the page </h1></center><form method="post" action="'+txn_url+'" name="f1">'+form_fields+'<script type="text/javascript">document.f1.submit()</script></body></html>'
res.writeHead(200, {'Content-Type':'text/html'})
res.write(html)
res.end()
})
})
Please use your own call back URL instead of https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=.
Above call back URL work only for app. So you need to replace your own call back URL in the parameter params['CALLBACK_URL'].

NodeJS params.Example not being used by #sendgrid/mail

Watson Assistant passes my params.finalemail and params.guestemail correctly. It looks like your #sendgrid/mail is not accepting the values of these params. Why is that?
Basically, Watson passes the $guest email as the "to" email address and the $finalemail contain the main body of the email.
I need my function to send an email with the information contained in the above varibles.
const sgMail = require('#sendgrid/mail');
/* Replace YOUR-SENDGRID-API-KEY-GOES-HERE with
the API Key you get from SendGrid.
*/
sgMail.setApiKey('apikey')
function sendmail(params) {
params.guestemail
params.finalemail
let msg = {}
msg.to = params.guestemail
msg.from = 'example#outlook.com'
msg.subject = 'Your Reservation'
msg.html = params.finalemail
sgMail.send(msg,(error, json) => {
if (error) {
console.log(error)
}
})
return { sent: 1 }
}
Sendgrid will send either text field or html not both. To send the message that you want you can add 'This message is HTML only.' in an html tag.

I'm trying to send emails using sendgrid in nodejs.But am getting "TypeError: object is not a function" error

Here is my code snippet
var sendgrid = require('sendgrid')('xxxxxx', 'xxxxxx');
var email = new sendgrid.Email();
email.addTo('xyz#gmail.com');
email.setFrom('xyz#gmail.com');
email.setSubject('welcome to send grid');
email.setHtml('<html><body>HELLO evryone ...,</body></html>');
sendgrid.send(email, function(err, json) {
if(!err)
{
console.log("mail sent successssss");
res.send({"status":0,"msg":"failure","result":"Mail sent successfully"});
}
else
{
console.log("error while sending mail")
res.send({"status":1,"msg":"failure","result":"Error while sending mail."});
}
});
Installed sendgrid throgh npm also.am getting "TypeError: object is not a function" error.MAy i know why.??
Version:--
sendgrid#3.0.8 node_modules\sendgrid
└── sendgrid-rest#2.2.1
It looks like you're using sendgrid#3.0.8 but trying to call on the sendgrid#2.* api.
v2 implementation: https://sendgrid.com/docs/Integrate/Code_Examples/v2_Mail/nodejs.html
v3 implementation:
https://sendgrid.com/docs/Integrate/Code_Examples/v3_Mail/nodejs.html
Give the v3 a go.
As for the type error:
v2
var sendgrid = require("sendgrid")("SENDGRID_APIKEY");
you're invoking a function
however you have v3 installed
require('sendgrid').SendGrid(process.env.SENDGRID_API_KEY)
and it's now an object
REQUESTED UPDATE:
I don't know too much about the keys given, but since they have tons of different supported libraries, it's completely possible that some of them use both while others use only one. If you really only have a USER_API_KEY nad PASSWORD_API_KEY, just use the user_api_key
Here is their source for the nodejs implementation module SendGrid:
function SendGrid (apiKey, host, globalHeaders) {
var Client = require('sendgrid-rest').Client
var globalRequest = JSON.parse(JSON.stringify(require('sendgrid-rest').emptyRequest));
globalRequest.host = host || "api.sendgrid.com";
globalRequest.headers['Authorization'] = 'Bearer '.concat(apiKey)
globalRequest.headers['User-Agent'] = 'sendgrid/' + package_json.version + ';nodejs'
globalRequest.headers['Accept'] = 'application/json'
if (globalHeaders) {
for (var obj in globalHeaders) {
for (var key in globalHeaders[obj] ) {
globalRequest.headers[key] = globalHeaders[obj][key]
}
}
}
The apiKey is attached to the header as an auth, and it looks like that's all you need.
Try following their install steps, without your own implementation,
1) (OPTIONAL) Update the development environment with your SENDGRID_API_KEY, for example:
echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env
========
2) Make this class and if you did the above use process.env.SENDGRID_API_KEY else put your USER_API_KEY
var helper = require('sendgrid').mail
from_email = new helper.Email("test#example.com")
to_email = new helper.Email("test#example.com")
subject = "Hello World from the SendGrid Node.js Library!"
content = new helper.Content("text/plain", "Hello, Email!")
mail = new helper.Mail(from_email, subject, to_email, content)
//process.env.SENDGRID_API_KEY if above is done
//else just use USER_API_KEY as is
var sg = require('sendgrid').SendGrid(process.env.SENDGRID_API_KEY)
var requestBody = mail.toJSON()
var request = sg.emptyRequest()
request.method = 'POST'
request.path = '/v3/mail/send'
request.body = requestBody
sg.API(request, function (response) {
console.log(response.statusCode)
console.log(response.body)
console.log(response.headers)
})

Meteor FS.Collection access collection on server

I'm using FS.Collection to upload short video file on a server and then send it as an attachment in email.
Inserting to the collection on server works and I can access collection items on the client, also, stream it directly with a path to the file Url - localhost:3000/cfs/files/videos/{{item_id}}
I wonder how to access collection on the server. I want to send an email with attachment in the following form and need to access path to file and filename on the server. I tried doing:
Email.send({
to: to,
from: from,
subject: subject,
text: text,
attachments:[{fileName:"video.mp4", filePath:"/cfs/files/videos/{{item_id}}"}]
});
It displays the attachment video player in the email, but with an error message, so I assume I'm not accessing a file correctly.
My Collection.js is simple:
var videoStore = new FS.Store.GridFS("videos");
Videos = new FS.Collection("videos", {
stores: [videoStore]
});
You can not use attachment by filePath of collectionFS. "/cfs/files/videos/{{item_id}}" is a virtual path, i.e. files don't exist in /cfs/files/videos, neither there is folder '/cfs/files/videos'.
You can use http path instead:
var ROOT_URL = process.env.ROOT_URL;
var rootUrl;
if (ROOT_URL.indexOf('/', ROOT_URL.length - 1) != -1) {
rootUrl = ROOT_URL.substring(0, ROOT_URL.length - 1);
} else {
rootUrl = ROOT_URL;
}
var attachments = [];
attachment = {
fileName: fileName(url),
filePath: rootUrl + "/cfs/files/videos/{{item_id}}"
};
attachments.push(attachment);
Email.send({
to: to,
from: from,
subject: subject,
text: text,
attachments: attachments
});

Resources