The following post from Twilio explains how to write and implement a function for sending the link of a recorded message to email.
https://www.twilio.com/blog/forward-voicemail-recordings-to-email
I want to attach to the voicemail recording rather than just send the link. Here is my attempt at modifying their code. Unfortunately it's causing a 500 error. I'm not very experience with NodeJS so perhaps you can help.
Dependencies for SendGrid and FS are included and this function worked perfectly until I modified it with FS, pathToAttachment, attachment variables and the attachments array.
//Initialize SendGrid Mail Client
const sgMail = require('#sendgrid/mail');
//FileSystem
const fs = require("fs");
// Define Handler function required for all Twilio Functions
exports.handler = function(context, event, callback) {
pathToAttachment = `${event.RecordingUrl}`;
attachment = fs.readFileSync(pathToAttachment).toString("base64");
// Build SG mail request
sgMail.setApiKey(context.SENDGRID_API_SECRET);
// Define message params
const msg = {
to: context.TO_EMAIL_ADDRESS,
from: context.FROM_EMAIL_ADDRESS,
fromname: 'Voicemail',
text: `URL is: ${event.RecordingUrl}`,
subject: `${event.From} (${event.country} / ${event.lang})`,
attachments: [
{
content: attachment,
filename: "Voicemail.wav",
disposition: "attachment"
}
]
};
// Send message
sgMail.send(msg)
.then(response => {
console.log("Neat.")
callback();
})
.catch(err => {
console.log("Not neat.")
callback(err);
});
};
This is how you modify the code from the Twilio blog:
Forward Voicemail Recordings to Email w/ Studio, Functions, & SendGrid
https://www.twilio.com/blog/forward-voicemail-recordings-to-email
.. to attach the email recording instead of link to it and how to add a from name as well as a from email address.
const request = require('request');
const sgMail = require('#sendgrid/mail');
exports.handler = function(context, event, callback) {
const fileUrl = event.RecordingUrl;
// Build SG mail request
sgMail.setApiKey(context.SENDGRID_API_SECRET);
request.get({ uri: fileUrl, encoding: null }, (error, response, body) => {
const msg = {
to: context.TO_EMAIL_ADDRESS,
from: {
"email": context.FROM_EMAIL_ADDRESS,
"name": `My company`
},
text: `Attached voicemail from ${event.From}.`,
subject: `${event.From}`,
attachments: [
{
content: body.toString('base64'),
filename: `MyRecording.wav`,
type: response.headers['content-type']
}
]
};
// Send message
sgMail.send(msg)
.then(response => {
console.log("Neat.")
callback();
})
.catch(err => {
console.log("Not neat.")
callback(err);
});
});
};
This is how you modify the code from
Related
I use twilio to send sms after a order is placed, but it isn't sending any sms and also not console logging anything.
Code: npm i twilio
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require("twilio")(accountSid, authToken);
exports.createOrder = (req, res) => {
const { orders, status, details } = req.body;
const order = new Order({
orders: orders,
status: status,
details: details,
});
order.save((error, order) => {
if (error) return res.status(400).json(error);
if (order) {
// if (res.status === 201) {
client.messages
.create({
body: "This is the ship that made the Kessel Run in fourteen parsecs?",
from: "+xxxxxxxxx",
to: "+xxxxxxxxxx",
})
.then((message) => console.log(message.sid));
// }
return res.status(201).json({ order });
}
});
};
LINK TO DOC (where I took the code) : https://www.twilio.com/docs/sms/quickstart/node
Twilio developer evangelist here.
There is likely an issue in sending your message, but the code you have is dropping errors, so you can't see what is going on. Try updating it to this:
client.messages
.create({
body: "This is the ship that made the Kessel Run in fourteen parsecs?",
from: "+xxxxxxxxx",
to: "+xxxxxxxxxx",
})
.then((message) => console.log(message.sid))
.catch(error => console.error(error));
Once you see what the error is, you will be able to fix it. My guess is that you have either configured your Account Sid and Auth Token incorrectly, or you are using a trial account and trying to send a message to a number you haven't verified yet, or you are trying to send a message to a country that isn't enabled.
I have setup a custom flow with cognito to send MFA codes via email using lambda triggers. I have just noticed though that the function does not appear to always work and the emails are not always sent when requesting to login although the lambda metrics do not report any failures?
I have added some logs and checked in cloudwatch and the if statement to send the email is being hit and the sendEmail() method is executed but i dont see any email being sent in my inbox (i have checked the junk/spam)
My account is still in a sandbox mode but i havent hit my daily limits so quite confused what is going on.
Any ideas what is happening?
Here is a screenshot of the cloudwatch logs in an instance where no email was sent:
here is my lambda trigger below for sending emails:
const crypto = require("crypto");
var aws = require("aws-sdk");
var ses = new aws.SES({ region: "eu-west-2" });
exports.handler = async(event, context, callback) => {
var verificationCode = 0;
//Only called after SRP_A and PASSWORD_VERIFIER challenges.
if (event.request.session.length == 2) {
const n = crypto.randomInt(0, 100000);
verificationCode = n.toString().padStart(6, "0");
const minimumNumber = 0;
const maximumNumber = 100000;
verificationCode = Math.floor(Math.random() * maximumNumber) + minimumNumber;
console.log('send email');
console.log('verificationCode: '+ verificationCode);
console.log('verificationCode: '+ event.request.userAttributes.email);
const params = {
Destination: { ToAddresses: [event.request.userAttributes.email] },
Message: {
Body: {
Html: {
Charset: 'UTF-8',
Data: `<html><body><p>This is your secret login code:</p>
<h3>${verificationCode}</h3></body></html>`
},
Text: {
Charset: 'UTF-8',
Data: `Your secret login code: ${verificationCode}`
}
},
Subject: {
Charset: 'UTF-8',
Data: 'Your secret login code'
}
},
Source: 'my verified email address'
};
await ses.sendEmail(params).promise().then((res) => {
console.log(res);
});
}
else {
//if the user makes a mistake, we pick code from the previous session instead of sending new code
const previousChallenge = event.request.session.slice(-1)[0];
verificationCode = previousChallenge.challengeMetadata;
}
//add to privateChallengeParameters, so verify auth lambda can read this. this is not sent to client.
event.response.privateChallengeParameters = { "verificationCode": verificationCode };
//add it to session, so its available during the next invocation.
event.response.challengeMetadata = verificationCode;
return event;
};
I am using Mailgun to send email when user click on button to book.
The following is my code:
import mailgun from 'mailgun-js';
const book = () => {
const DOMAIN = 'azaleflowerbar.com';
const api_key = '**********5d721598c7d08095-07bc7b05-******'; //hidden for privacy
const mg = mailgun({apiKey: api_key, domain: DOMAIN, host: "api.eu.mailgun.net"});
const data = {
from: 'Excited User <me#samples.mailgun.org>',
to: 'myemail#gmail.com, ',
subject: 'Hello',
text: 'Testing some Mailgun awesomness!'
};
mg.messages().send(data, function (error, body) {
if (error) {
console.log(error)
}
console.log(body);
});
}
What i get though from console.log(body) is "undefined".
I have tried this same code with the sandbox and it works fine (the message is queued).
Also, mailgun DNS for my domain are verified.
I am in touch with mailgun support but they cannot be of any help.
Any help would be much appreciated
I have a shopify store mystore and I have an nodejs app myapp. I need to do is when something happens on mystore a webhook will be created/registered in my nodejs app. I have tried https://www.npmjs.com/package/#shopify/koa-shopify-webhooks this package but it is not working for me and I don't think that it is the same thing that I want. I just want that when let suppose order is created in store a webhook is registered.
if you just have to register a webhook you can use this code.
You just have to change the webhook topic and the endpoint.
This is for orders/create webhook registration
add shopify-api-node and request-promise packages and require them
const ShopifyAPIClient = require("shopify-api-node");
const request = require("request-promise");
then
const createOrderWebhook = await registerWebhook(yourShopDomain, yourShopAccessToken, {
topic: "orders/create",
address: "Your node app end point" //www.example.com/webhooks/createOrder,
format: "json",
});
add your registerWebhook function
const registerWebhook = async function (shopDomain, accessToken, webhook) {
const shopify = new ShopifyAPIClient({
shopName: shopDomain,
accessToken: accessToken,
});
const isCreated = await checkWebhookStatus(shopDomain, accessToken, webhook);
if (!isCreated) {
shopify.webhook.create(webhook).then(
(response) => console.log(`webhook '${webhook.topic}' created`),
(err) =>
console.log(
`Error creating webhook '${webhook.topic}'. ${JSON.stringify(
err.response.body
)}`
)
);
}
};
for checking the webhook already not created at Shopify you can use following code
const checkWebhookStatus = async function (shopDomain, accessToken, webhook) {
try {
const shopifyWebhookUrl =
"https://" + shopDomain + "/admin/api/2020-07/webhooks.json";
const webhookListData = {
method: "GET",
url: shopifyWebhookUrl,
json: true,
headers: {
"X-Shopify-Access-Token": accessToken,
"content-type": "application/json",
},
};
let response = await request.get(webhookListData);
if (response) {
let webhookTopics = response.webhooks.map((webhook) => {
return webhook.topic;
});
return webhookTopics.includes(webhook.topic);
} else {
return false;
}
} catch (error) {
console.log("This is the error", error);
return false;
}
};
Happy coding :)
You can not create/register a new webhook when the order created.
Webhooks are a tool for retrieving and storing data from a certain event. They allow you to register an https:// URL where the event data can be stored in JSON or XML formats. Webhooks are commonly used for:
Placing an order
Changing a product's price
Notifying your IM client or your pager when you are offline
Collecting data for data-warehousing
Integrating your accounting software
Filtering the order items and informing various shippers about the order
Removing customer data from your database when they uninstall your app
I am learning all of this as I go. The goal is to simply send an email using variables, and here's the code that I have so far in test.js:
const mailgunSdk = require('mailgun-js');
const apiKey = 'MAILGUN_API_KEY';
const domain = 'MAILGUN_DOMAIN';
const mailgun = mailgunSdk({
apiKey,
domain
});
exports.handler = async(event, context, callback) => {
//console.log(event.body)
//const data = JSON.parse(event.body)
let response
try {
/* Send email to recicipent */
response = await mailgun.messages().send({
from: 'Reginald Fromington <mg#fromaddress.com>',
to: 'bobloblaw#gmail.com',
subject: 'Hello',
text: event.messageText
})
} catch (e) {
//console.log('Err', e)
return {
statusCode: e.statusCode || 500,
//body: JSON.parse({
// error: e.message
//})
}
}
return {
statusCode: 200,
body: JSON.stringify({
result: response.message
})
}
}
Using Postman, I can actually get a message in my inbox if I have text: as a string, such as text: 'Thank you for your email' if I'm running the function without any params. However, if I want to use a variable, I have no idea how to pass them into the function. I've tried text: event.messageText, text: response.messageText, text: mailgun.messageText, and every possible combination of variables that I could imagine to pull from.
Most of the documentation that I could find is outdated or doesn't address this issue. I also don't really know how to google this issue because again, I'm new to all of this.
Thanks,
-Andrew
Attempting to pass parameters into Lambda Function