I'm trying to send an email with custom data.
async function sendEmailToSalesTeamOnBookingDemoClass(email,name,phoneNumber,utmSource,utmTerm,utmMedium,deviceType,browser,referrer) {
try {
let emailMe = "abc#gmail.com"
const ses = new AWS.SES({ apiVersion: "2010-12-01" });
const params = {
Destination: {
ToAddresses: [emailMe]
},
Source: senderEmail,
Template: "Sales_Email_Demo",
TemplateData : JSON.stringify({
"name": name,
"email": email,
"phone": phoneNumber,
"utmSource":utmSource,
"utmTerm":utmTerm,
"utmMedium":utmMedium,
"browser":browser,
"referrer":referrer,
"deviceType":deviceType
}),
Tags: [
{
Name: 'SomeName',
Value: 'info'
}
]
};
const sendEmailReceiver = ses.sendTemplatedEmail(params).promise();
sendEmailReceiver
.then(data => {
console.log(senderEmail,emailMe)
console.log("Email submitted to SES", data);
})
.catch(error => {
console.log("Email not submitted to SES:" + error);
});
}
catch (e) {
console.error(`Error: ${e}`);
}
}
The response says that the email was sent successfully.
Email submitted to SES {
ResponseMetadata: { RequestId: 'c08b9948-7be3-465d-a72c-fcca23f9f059' },
MessageId: '010901793bd95a02-813072dc-bb87-4b65-91c4-03f7f29dcbd0-000000'
}
But there is no email received even though the sender email has been verified and tested. Is there something wrong with my template?
{
"Template": {
"TemplateName": "Sales_Email_Demo",
"SubjectPart": "some subject!",
"HtmlPart": "<html> <body><p>Hello,</p><p>Details:</p><p>Name:{{name}}</p><p>Phone Number: {{phoneNumber}}</p><p>Email Id: {{emailId}}</p><p>Source: {{utmSource}}</p><p>Medium: {{utmMedium}}</p><p>Term:{{utmTerm}}</p><p>Device:{{deviceType}}</p><p>Browser:{{browser}}</p><p>Referrer: {{referrer}}</p></body></html>"
}
}
I figured it out. The issue was with the template. The sending and receiving variables were named differently.
Related
I need assistance in fetching data back to client as soon as it is posted to the database without reloading the page. The structure I have at present only shows the posts on page reload. Below are my codes.
const [pst, setPst] = useState([]);
const handleSubmit = async (e) => {
e.preventDefault();
const v2 = PST_REGEX.test(pst);
if (!v2) {
// setErrMsg("Invalid Entry");
return;
}
try {
const response = await axios
.post(DASHBOARD_URL, JSON.stringify({ pst }), {
headers: { "Content-Type": "application/json" },
withCredentials: true,
})
} catch (err) {
console.log(err)
}
};
Post Controller
const handleNewPost = async (req, res) => {
const { pst } = req.body;
if (!pst) return res.status(400).json({ message: "Field cannot be blank" });
try {
//create and store the new post
const result = await Userpost.create({
post: pst,
});
console.log(result);
res.status(201).json({ success: `New post ${pst} created!` });
} catch (err) {
res.status(500).json({ message: err.message });
}
};
There are some ways from which you can achieve your solution.
Method 1:
You can return newly created data from backend as success response. Lets assume you got response as follow:
{
"message": "Data created Successfully",
"status" : "201",
"data": [{
"id": "1234",
"title": "Blog title",
"description" : "Blog description"
}]
}
Then you can simply add response to you previous state as:
setPst([...pst, ...message.data]) // message.data is response from your endpoint
Method 2:
You can use socket io for real time experience: https://socket.io/
I have one function that is responsible of creating order using razorpay and verify that order .
The code for that function is : -
const paymentMethod = async ()=>{
if(!isAuthenticated())
{
toast.error('Please signin to continue');
history.push('/signin')
// return <Redirect to='/signin' />
return;
}
try{
// console.log(JSON.stringify(total));
const obj = {
amount:total
}
let data = await fetch('http://localhost:3100/api/checkout',{
method:'POST',
headers:{
"content-type":"application/json",
Accept:"application/json"
},
body: JSON.stringify(obj)
})
let {order} = await data.json()
console.log(order)
console.log(order.amount)
const options = {
key: "rzp_test_cXj3ybg8fawS9Y",
amount: order.amount,
currency: "INR",
name: "YO! Merchandise",
description: "Pay Please",
image:yo,
order_id: order.id,
callback_url: "http://localhost:3100/api/paymentverification",
prefill: {
name: "Aakash Tiwari",
email: "tiwaryaakash00#gmail.com",
contact: "8750043604"
},
notes: {
address: "Razorpay Corporate Office"
},
theme: {
color: "#13C962"
}
};
let rzp1 = await new window.Razorpay(options);
rzp1.open();
}
catch(err){
console.log(err)
}
}
But this function when call callback_url upon successfull payment it is not passing the payment_id,order_id etc. other neccessary details.
when i try to console.log there the req.body is always empty.
How do you send attachments with the Microsoft graph outlook API? I understand everything for sending attachments up until the content bytes. The files that I need to send are a word document a pdf and a jpeg Is it asking me to turn the file into bytes, if so how would I do that? I am using node.js and I have the following code:
exports.send_mail = async function(req, res, next) {
let parms = { title: 'Inbox', active: { inbox: true } };
const accessToken = await authHelper.getAccessToken(req.cookies, res);
const userName = req.cookies.graph_user_name;
if (accessToken && userName) {
parms.user = userName;
// Initialize Graph client
const client = graph.Client.init({
authProvider: (done) => {
done(null, accessToken);
}
});
//read test.html
//so you have to wait for the file to read then send it
message = fs.readFileSync('views/test.html', 'utf8');
console.log(rawImage.data.toString('utf8'))
try {
mailMess ={
message:{
subject: 'This is a test',
body:{
ContentType: 'HTML',
Content: message
},
ToRecipients:[
{
EmailAddress:{
Address: 'name#email.com'
}
}
],
"attachments": [
{
"#odata.type": "#microsoft.graph.fileAttachment",
"name": "attachment.jpeg",
"contentBytes": "not sure what to put here"
}
]
}
}
//sendmail
const result = await client
.api('/me/sendmail')
.version('v1.0')
.post(mailMess);
res.status('202')
parms.messages = result.value;
res.redirect('/');
} catch (err) {
parms.message = 'Error retrieving messages';
parms.error = { status: `${err.code}: ${err.message}` };
parms.debug = JSON.stringify(err.body, null, 2);
res.render('error', parms);
}
} else {
// Redirect to home
res.redirect('/');
}
}
I found out that param takes the file encoded as base64
I am connecting GraphQL with REST endpoints, I confirmed that whenever I am calling http://localhost:3001/graphql it is hitting REST endpoint and it is returning JSON response to GraphQL server, but I am getting an empty response from GraphQL server to GUI as follows:
{
"data": {
"merchant": {
"id": null
}
}
}
Query (decoded manually):
http://localhost:3001/graphql?query={
merchant(id: 1) {
id
}
}
Below is how my GraphQLObjectType looks like:
const MerchantType = new GraphQLObjectType({
name: 'Merchant',
description: 'Merchant details',
fields : () => ({
id : {
type: GraphQLString // ,
// resolve: merchant => merchant.id
},
email: {type: GraphQLString}, // same name as field in REST response, so resolver is not requested
mobile: {type: GraphQLString}
})
});
const QueryType = new GraphQLObjectType({
name: 'Query',
description: 'The root of all... queries',
fields: () => ({
merchant: {
type: merchant.MerchantType,
args: {
id: {type: new GraphQLNonNull(GraphQLID)},
},
resolve: (root, args) => rest.fetchResponseByURL(`merchant/${args.id}/`)
},
}),
});
Response from REST endpoint (I also tried with single object in JSON instead of JSON array):
[
{
"merchant": {
"id": "1",
"email": "a#b.com",
"mobile": "1234567890"
}
}
]
REST call using node-fetch
function fetchResponseByURL(relativeURL) {
return fetch(`${config.BASE_URL}${relativeURL}`, {
method: 'GET',
headers: {
Accept: 'application/json',
}
})
.then(response => {
if (response.ok) {
return response.json();
}
})
.catch(error => { console.log('request failed', error); });
}
const rest = {
fetchResponseByURL
}
export default rest
GitHub: https://github.com/vishrantgupta/graphql
JSON endpoint (dummy): https://api.myjson.com/bins/8lwqk
Edit: Adding node.js tag, may be issue with promise object.
Your fetchResponseByURL function get empty string.
I think the main problem is that you are using wrong function to get the your JSON string, please try to install request-promise and use it to get your JSON string.
https://github.com/request/request-promise#readme
something like
var rp = require('request-promise');
function fetchResponseByURL(relativeURL) {
return rp('https://api.myjson.com/bins/8lwqk')
.then((html) => {
const data = JSON.parse(html)
return data.merchant
})
.catch((err) => console.error(err));
// .catch(error => { console.log('request failed', error); });
}
In this case using data.merchant solved my problem. But the above suggested solution i.e., use of JSON.parse(...) might not be the best practice because if there are no object in JSON, then expected response might be as follows:
{
"data": {
"merchant": null
}
}
Instead of fields to be null.
{
"data": {
"merchant": {
"id": null // even though merchant is null in JSON,
// I am getting a merchant object in response from GraphQL
}
}
}
I have updated my GitHub: https://github.com/vishrantgupta/graphql with working code.
When I write the alphabet on my facebook bot, my bot wait to respond.
I write for example : I write "a"... bot respond "a", I write "b"... bot respond "b", etc...
But, for example on the letter "l", the bot waits to respond, and resume after about some minutes :
after about some minutes, the bot responds :
I use the official code, from https://developers.facebook.com/docs/messenger-platform/guides/quick-start/
app.js
app.get('/webhook', function(req, res) {
if (req.query['hub.mode'] === 'subscribe' &&
req.query['hub.verify_token'] === CONFIGURATION.webhook_token) {
console.log("Validating webhook");
res.status(200).send(req.query['hub.challenge']);
} else {
console.error("Failed validation. Make sure the validation tokens match.");
res.sendStatus(403);
}
});
app.post('/webhook', function (req, res) {
let data = req.body;
// Make sure this is a page subscription
if (data.object === 'page') {
// Iterate over each entry - there may be multiple if batched
data.entry.forEach(function(entry) {
let pageID = entry.id;
let timeOfEvent = entry.time;
// Iterate over each messaging event
entry.messaging.forEach(function(event) {
if (event.message) {
receivedMessage(event);
} else {
console.log("Webhook received unknown event: ", event);
}
});
});
// Assume all went well.
//
// You must send back a 200, within 20 seconds, to let us know
// you've successfully received the callback. Otherwise, the request
// will time out and we will keep trying to resend.
res.sendStatus(200);
}
});
function receivedMessage(event) {
let senderID = event.sender.id;
let recipientID = event.recipient.id;
let timeOfMessage = event.timestamp;
let message = event.message;
console.log("Received message for user %d and page %d at %d with message:",
senderID, recipientID, timeOfMessage);
console.log(JSON.stringify(message));
let messageId = message.mid;
let messageText = message.text;
let messageAttachments = message.attachments;
if (messageText) {
// If we receive a text message, check to see if it matches a keyword
// and send back the example. Otherwise, just echo the text we received.
switch (messageText) {
case 'generic':
sendGenericMessage(senderID);
break;
default:
sendTextMessage(senderID, messageText);
}
} else if (messageAttachments) {
sendTextMessage(senderID, "Message with attachment received");
}
}
function sendGenericMessage(recipientId) {
let messageData = {
recipient: {
id: recipientId
},
message: {
attachment: {
type: "template",
payload: {
template_type: "generic",
elements: [{
title: "rift",
subtitle: "Next-generation virtual reality",
item_url: "https://www.oculus.com/en-us/rift/",
image_url: "http://messengerdemo.parseapp.com/img/rift.png",
buttons: [{
type: "web_url",
url: "https://www.oculus.com/en-us/rift/",
title: "Open Web URL"
}, {
type: "postback",
title: "Call Postback",
payload: "Payload for first bubble",
}],
}, {
title: "touch",
subtitle: "Your Hands, Now in VR",
item_url: "https://www.oculus.com/en-us/touch/",
image_url: "http://messengerdemo.parseapp.com/img/touch.png",
buttons: [{
type: "web_url",
url: "https://www.oculus.com/en-us/touch/",
title: "Open Web URL"
}, {
type: "postback",
title: "Call Postback",
payload: "Payload for second bubble",
}]
}]
}
}
}
};
callSendAPI(messageData);
}
function sendTextMessage(recipientId, messageText) {
let messageData = {
recipient: {
id: recipientId
},
message: {
text: messageText
}
};
callSendAPI(messageData);
}
function callSendAPI(messageData) {
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: CONFIGURATION.access_token },
method: 'POST',
json: messageData
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
let recipientId = body.recipient_id;
let messageId = body.message_id;
console.log("Successfully sent generic message with id %s to recipient %s",
messageId, recipientId);
} else {
console.error("Unable to send message.");
console.error(response);
console.error(error);
}
});
}
let server = app.listen(port, function () {
InterfaceLogin.process();
console.log('App listening on port 8080!');
});
server.timeout = 1000;
In my console, During the last respond I see :
Received message for user xxx and page xxx at xxx with message:
{"mid":"mid.$xxx","seq":xxxx,"text":"k"}
Successfully sent generic message with id mid.$xxx to recipient xxxxx
the bot don't respond, and after some minutes I see :
Received message for user xxx and page xxx at xxx with message:
{"mid":"mid.$xxx","seq":xxxx,"text":"l"}
Successfully sent generic message with id mid.$xxx to recipient xxxx
Webhook received unknown event: { sender: { id: 'xxx' },
recipient: { id: 'xxx' },
timestamp: xxx,
delivery:
{ mids: [ 'mid.$xxx' ],
watermark: xxx,
seq: 0 } }
the bots responds
My last respond is :
Received message for user xxx and page xxx at xxx with message:
{"mid":"mid.$xxx","seq":xx,"text":"k"}
Successfully sent generic message with id mid.$xxx to recipient xxx
Received message for user xxx and page xxx at xxx with message:
{"mid":"mid.$xxx","seq":xx,"text":"l"}
Successfully sent generic message with id mid.$xxx to recipient xxxx
Webhook received unknown event: { sender: { id: 'xxx' },
recipient: { id: 'xxx' },
timestamp: xxx,
delivery:
{ mids: [ 'mid.$xxx' ],
watermark: xxx,
seq: 0 } }
The messenger bot platform has rate limit, if you exceed it the requests will queue up and execute later.
https://developers.facebook.com/docs/messenger-platform/reference/send-api/