Add custom text to email body automatically when user clicks Reply button - node.js

I am parsing incoming emails to my domain using Mailslurp API and I want to get only the email body without the email signature. I struggled a lot finding out how to recognize signature from the email body but I could not find a satisfying solution till now.
Another alternative I plan to do is add a custom line to the email body like --- reply above this line --- when the receiver of my email clicks on reply button. The user can then add the reply above that line and I can easily extract the content above that line. Do I need to pass that line in the email headers while sending the email? If yes then can anyone please tell me how to pass the same?
Can someone please guide me about how to achieve this? I think this question is a possible duplicate of this question but since that question is unanswered thought of asking this again.
Any help is highly appreciated.

Maybe this the examle (at https://www.mailslurp.com/guides/extract-email-content/) helps. Perhaps adjust this for your usage.
it('can extract email content', async () => {
const mailslurp = new MailSlurp(config);
const inbox1 = await mailslurp.createInbox();
const inbox2 = await mailslurp.createInbox();
const to = [inbox2.emailAddress]
const body = "Hi there. Your code is: 123456"
await mailslurp.sendEmail(inbox1.id, { to, body })
// wait for email
const email = await mailslurp.waitController.waitForLatestEmail(inbox2.id, timeoutMillis, true)
const pattern = "code is: ([0-9]{6})"
expect(email.body).toContain("Your code is")
const result = await mailslurp.emailController.getEmailContentMatch({ pattern }, email.id)
expect(result.matches).toHaveLength(2);
expect(result.matches[0]).toEqual("code is: 123456")
expect(result.matches[1]).toEqual("123456")
// now do something with the code
})

Related

Can't receive email with attachment from mailgun

I create router from mailgun to forward emails to my website endpoint www.example.com/messages
and I received emails successfully when it only text but when i attach file to this email, I don't receive any thing and the request body is empty
export const incomingEmails = async (req, res) => {
const from = req.body.from.split('<')[0].trim();
const sender = req.body.sender;
const recipient = req.body.recipient;
const subject = req.body.subject;
const html = req.body['stripped-html'];
try {
const incomingEmail = new Support({
from,
sender,
recipient,
subject,
html
})
await incomingEmail.save();
res.sendStatus(200)
} catch (error) {
res.status(500)
next(new Error('something went wrong'))
}}
i'm using url encoded middle ware
app.use(express.urlencoded())
note the stack I use is node and express at at backend
I ran into the same issue and I figured out why. I used the forward method to receive emails on my backend. The forward method only works when there is no attachment. With attachments, Mailgun will return an empty body because Mailgun has to first store the attachments, which is asynchronous.
In order to solve this issue, you have to use the store method instead of the forward method:
store(notification endpoint)
Stores the message temporarily (for up to 3 days) on Mailgun’s servers
so that you can retrieve it later. This is helpful for large
attachments that may cause time-outs or if you just want to retrieve
them later to reduce the frequency of hits on your server.
You have to edit your route in the Mailgun web app: go under "Receiving" in the menu and then edit your existing route.
Instead of entering:
forward("http://example.com/callback")
You enter:
store(notify="http://example.com/callback")

How to get impression from google ads using google-ads-node( met one issue; INVALID CUSTOMER ID even though it is set correctly.)

Hope you are safe and good for this pandemic time.
I am developing some functional to fetch data from google ads using google-ads-node.
But for now I met one issue.
Error: 3 INVALID_ARGUMENT: Invalid customer ID '... .... ...'.
However it is set correctly on ads account.
Please understand me messy picture.
The code I used like this.
const auth = await authenticateGoogle(`keys/${process.env.GOOGLE_YT3_API_CREDENTIAL_PATH}`, 'installed');
const client = new GoogleAdsClient({
access_token: auth.credentials.access_token,
developer_token: process.env.DEV_TOKEN,
parseResults: true,
});
const service = client.getService("GoogleAdsService", { useStreaming: true });
const request = new SearchGoogleAdsStreamRequest();
request.setQuery(`
SELECT
campaign.resource_name,
metrics.impressions,
segments.date
FROM
campaign
WHERE
segments.date BETWEEN "2019-01-01" AND "2020-01-01"
`);
request.setCustomerId(process.env.CUSTOMER_ID);
const call = service.searchStream(request);
const chunks = [];
call.on("error", err => reject(err));
call.on("data", (chunk) => chunks.push(chunk));
call.on("end", () => resolve(chunks));
Would you help me how I can figure out this issue please?
Thank you.
The only thing you need is to pass the CustomerID without dash (-). More specifically, you just need passing the CustomerID with XXXXXXXXXX format instead of XXX-XXX-XXXX.
google-ads-api need client_id and login_customer_id.
i think CUSTOMER_ID need to change as "client_customer_Id" not a "login_customer_id"
For the ones that ended up here in 2021+.. the "google-ads-node" does not recieve any more support from Opteo, they now support the "google-ads-api" lib that themselves made.

awaitMessages inside async function discord.js

I am fairly new to async and I am trying to get the response from a user to a bot via a private message. I have done this before in sync, but not async. I have working code that properly awaits reactions that I worked into the following code, but it doesn't seem to work the same way (obviously) as I am getting (node:10080) UnhandledPromiseRejectionWarning: TypeError: msg.awaitMessages is not a function as an error when I run it.
I've looked around in trying to find awaitMessages to work for a private message inside an async function but it looks to be more complicated than putting something like the answer to this question Await reply in private message discord.js
async function cardExists() {
let matchedcards = []
let msg = await message.author.send(`Please provide the cardnames that you would like to add to '${userdeckname}'.\n\n**NOTE:** Please separate each card with a comma and space, like so "Pact of Darkness, Aquos Slam, Karmic Balance"`)
const filter = m => m.author.id === message.author.id
const reply = await msg.awaitMessages(filter, { max: 1 })
.catch(console.error);
let cardsToAdd = reply.first()
let usercardnamearray = cardsToAdd.content.split(", ")
I simply want the question to be asked, and await the user to reply in a private message to the discord bot. Some code that runs after the snippet above (once cardsToAdd is declared) ends up checking if each card in the list exists in a mysql database and pushes the cards that succeed to an array to be used later and sends the cards that fail to the private chat.
Thanks for your help in advance!
Use msg.channel.awaitMessages instead of msg.awaitMessages according to the official documentation.

Dialogflow - Dynamic text response

How can I set dynamic args in Text response?
not from user phrases
I have a case:
bot says: "Do you find a work?"
user says: "Yes"
Text response:
bot says: "I can offer you vacancy {random vacancy}"
You can't do it with a default text response, in fact, you need to enable webhook call for that intent in the fulfillment section. I'll show you how my intent looks like.
Here you have the webhook code:
'use strict';
const http = require('http');
const request2 = require('request');
exports.dialogflowFirebaseFulfillment = (req, res) => {
console.log('Dialogflow Request body: ' + JSON.stringify(req.body));
let action = req.body.queryResult['intent']['displayName'];
switch(action){
case "work":
// Get the city from a database
let city="Randomcity";
// Get the job from a database
let job="randomjob";
res.send(JSON.stringify({ 'fulfillmentText': "I can offer you this fantastic job in "+city+" city, doing "+job}));
break;
//Add more cases if you have more intents
}
}
And this is the result:
There are two cases :
1. If you want to return random arguments, then you can simply set all possible arguments in the responses and DialogFlow will randomly select a response a send it to user.
If the arguments are based on some criteria, then you need to enable webhook and you need to return the response from the webhook. This is the recommended option. And this is how fulfillment works.
Hope it helps.

Google Docs embed answering form

I want to embed a form in an email that works both in a web browser and the gmail app, using google docs.
I have been able to embed it and use it in different browsers with the following code, but I can't use it in the app.
The problem is that I want the user to respond by ticking either Yes or No, and clicking an Accept button.
Could you please help me?
Thanks in advance
form.setRequireLogin(false);
var url = form.getPublishedUrl();
var response = UrlFetchApp.fetch(url);
var htmlBody = HtmlService.createHtmlOutput(response).getContent();
MailApp.sendEmail(responsableDirecto,
"Course request",
"",
{
name: 'Course request confirmation'+""+program+""+name,
htmlBody: htmlBody,
attachments: [documetoDatos],
});

Resources