I am trying to attach pdf in email using Amazon ses.sendEmail. But i don't know the param key to do it. Without attachment it is working perfectly. Here is what I have tried.
` var ses = new AWS.SES()
var params = {
Destination: {
ToAddresses: [
'xxx',
]
},
Message: {
Body: {
Html: {
Data: msg,
Charset: 'UTF-8'
}
},
Subject: { /* required */
Data: 'Test Mail',
Charset: 'UTF-8'
}
},
Attachment:{
},
Source: 'yyy'
};
ses.sendEmail(params, function(err, data) {
if (err) {// an error occurred}
oDialog.close();
MessageToast.show("Email not sent. Some problem occurred!");
}
else {
oDialog.close();
MessageToast.show("Email sent successfully!");
}
});`
For anyone else that want to add attachments to an SES email, here is what I did for a lambda in NodeJS: use Nodemailer with the SES transport.
npm install --save nodemailer
and in the code:
// create Nodemailer SES transporter
const transporter = nodemailer.createTransport({
SES: new AWS.SES({
apiVersion: '2010-12-01',
region: "eu-west-1", // SES is not available in eu-central-1
})
});
const emailTransportAttachments = [];
if (attachments && attachments.length !== 0) {
emailTransportAttachments = attachments.map(attachment => ({
filename: attachment.fileName,
content: attachment.data,
contentType: attachment.contentType,
}));
}
const emailParams = {
from,
to,
bcc,
subject,
html,
attachments: emailTransportAttachments,
};
return new Promise((resolve, reject) => {
transporter.sendMail(emailParams, (error, info) => {
if (error) {
console.error(error);
return reject(error);
}
console.log('transporter.sendMail result', info);
resolve(info);
});
});
Currently, you can only send attachments if you use the raw email API, e.g.:
var ses_mail = "From: 'Your friendly UI5 developer' <" + email + ">\n"
+ "To: " + email + "\n"
+ "Subject: AWS SES Attachment Example\n"
+ "MIME-Version: 1.0\n"
+ "Content-Type: multipart/mixed; boundary=\"NextPart\"\n\n"
+ "--NextPart\n"
+ "Content-Type: text/html; charset=us-ascii\n\n"
+ "This is the body of the email.\n\n"
+ "--NextPart\n"
+ "Content-Type: text/plain;\n"
+ "Content-Disposition: attachment; filename=\"attachment.txt\"\n\n"
+ "Awesome attachment" + "\n\n"
+ "--NextPart";
var params = {
RawMessage: { Data: new Buffer(ses_mail) },
Destinations: [ email ],
Source: "'Your friendly UI5 developer' <" + email + ">'"
};
var ses = new AWS.SES();
ses.sendRawEmail(params, function(err, data) {
if(err) {
oDialog.close();
MessageToast.show("Email sent successfully!");
}
else {
oDialog.close();
MessageToast.show("Email sent successfully!");
}
});
Related
I'm creating a contact form using Nextjs and SendGrid, according to this header status
202
{
server: 'nginx',
date: 'Thu, 08 Dec 2022 16:29:25 GMT',
'content-length': '0',
connection: 'close',
'x-message-id': 'CaVdpVAURza6JrUF7yIQQA',
'access-control-allow-origin': 'https://sendgrid.api-docs.io',
'access-control-allow-methods': 'POST',
'access-control-allow-headers': 'Authorization, Content-Type, On-behalf-
of, x-sg-elas-acl',
'access-control-max-age': '600',
'x-no-cors-reason':
'https://sendgrid.com/docs/Classroom/Basics/API/cors.html',
'strict-transport-security': 'max-age=600; includeSubDomains'
}
the email is sent but I find nothing in my inbox,
and this error occurs in the terminal
API resolved without sending a response for /api/contact, this may result in stalled requests.
I don't know what mistake I've done but. I invite you to look at my code bellow:
API :
import sgMail from "#sendgrid/mail";
export default function handler(req, res) {
if (req.method !== "POST") {
res.status(405).json({ message: "INVALID_METHOD" });
return;
}
// Variables from the client side
var name = req.body.name;
var email= req.body.email;
var subject= req.body.subject;
var content = req.body.content;
// auto line break message
const message = content
.replace(/\n/g, "<br>")
.replace(/\r/g, "<br>")
.replace(/\t/g, "<br>")
.replace(/<(?!br\s*\/?)[^>]+>/g, "");
// giving the api key API
sgMail.setApiKey(process.env.KEY_SENDGRID);
// Creating message
const sendGridMail = {
to: "arotiana4612#gmail.com",
from: "kaspersky2mahanaima#gmail.com",
subject: subject,
templateId: "d-b48909edf062437e8442f861a4c8be29",
dynamic_template_data: {
name: name,
email: email,
subject: subject,
content: message,
},
};
// SENDING MESSAGE VIA SENDGRID
(async () => {
try {
await sgMail.send(sendGridMail)
.then((response) => {
console.log(response[0].statusCode)
console.log(response[0].headers)
})
.catch((error) => {
console.error(error)
})
} catch (err){
console.error(err);
res.status(500).json({
error:JSON.stringify(err),
message: "ERROR_WITH_SENDGRID",
});
}
})();
}
And this is the method from the client side that from which I get the data:
const onSubmit: SubmitHandler<Inputs> = async (formData) => {
if (!isLoading) {
setIsLoading(true);
const response = await fetch("/api/contact", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(formData),
});
const result = await response.json();
setIsLoading(false);
if (!response.ok) {
console.log("error sending email:",result);
} else {
console.log("ok");
}
return result;
}
};
I want to receive the mail in my inbox. Your help would be very appreciated, I'm strugling
can someone help me with dialogflow cx webhooks and add data to Firestore, this is my index.js code but it does not store in the database. Thanks
Hello, can someone help me with dialogflow cx webhooks and add data to Firestore, this is my index.js code but it does not store in the database. Thanks
const Firestore = require('#google-cloud/firestore');
const PROJECTID = 'ia-proyecto';
const firestore = new Firestore({
projectId: PROJECTID,
timestampsInSnapshots: true,
});
exports.db_datos_personales = (req, res) => {
function replaceAll(string, search, replace) {
return string.split(search).join(replace);
}
console.log('Dialogflow Request body: ' + JSON.stringify(req.body));
let tag = req.body.fulfillmentInfo.tag;
console.log('Tag: ' + tag);
console.log('Session Info Parameters: ' + JSON.stringify(req.body.sessionInfo.parameters));
//
if (tag === 'nombre') {
const COLLECTION_NAME = 'Datos_Personales';
let Nombre_Usuario = replaceAll(JSON.stringify(req.body.sessionInfo.parameters['nombre_usuario']), '"', '');
let Ciudad_Usuario = replaceAll(JSON.stringify(req.body.sessionInfo.parameters['ciudad_usuario']), '"', '');
console.log('Nombre usuario: ' + Nombre_Usuario);
console.log('Ciudad usuario: ' + Ciudad_Usuario);
const data = {
Nombre_Usuario: Nombre_Usuario,
Ciudad_Usuario: Ciudad_Usuario,
};
console.log(JSON.stringify(data));
var answer = 'Welcome to the Cloud Audio family, '+ Nombre_Usuario +'! Enjoy our services.';
return firestore.collection(COLLECTION_NAME)
.set(data)
.then(doc => {
return res.status(200).send({
fulfillmentResponse: {
messages: [{
text: {
text: [answer]
}
}]
}
});
}).catch(err => {
console.error(err);
return res.status(404).send({ error: 'unable to store', err });
});
//
} else if (tag === 'pregunta') {
const COLLECTION_NAME = 'Pregunta_Usuario';
let pregunta_usuario = replaceAll(JSON.stringify(req.body.sessionInfo.parameters['pregunta_usuario']), '"', '');
console.log('Pregunta Usuario: ' + pregunta_usuario);
const data = {
pregunta_usuario: pregunta_usuario
};
console.log(JSON.stringify(data));
var answer = 'Your plan has been changed to the '+ pregunta_usuario + ' service.';
return firestore.collection(COLLECTION_NAME)
.doc(phone_number)
.update(data)
.then(doc => {
return res.status(200).send({
fulfillmentResponse: {
messages: [{
text: {
text: [answer]
}
}]
}
});
}).catch(err => {
console.error(err);
return res.status(404).send({ error: 'unable to update field', err });
});
}
};
I hope to have a solution, since I was more than a week and I can't find anything.
I have a simple app with two routes, which I use locally and on IBM Cloud/Cloud Foundry (512 M RAM)
/
returns "Hello World!" & 200 locally and on the IBM Cloud
/getData
returns some data locally & 200
on cloud it returns 400, no logs
Edit:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
var cors = require("cors"); // Cors
app.use(cors());
var port = process.env.PORT || 3000;
app.get('/', (req, res) => res.send('Hello World!'))
// *************** GETDATA ***************************************
app.get('/getData', function (req, res) {
var request = require("request");
var httpHeaderOptions = {
accept: "application/json",
"content-type": "application/json",
apikey: req.headers.apikey
};
var restoptions = {
method: "GET",
url: req.headers.route,
headers: httpHeaderOptions
};
// console.log("headers: " + JSON.stringify(req.headers));
// console.log("GET DOCS: \n", JSON.stringify(restoptions));
request(restoptions, function (error, response, body) {
console.log(typeof (body));
body_json = JSON.parse(body);
if (error) {
console.error("Failed: %s", error.message);
body = {
"error": error.message
};
res.status(400).json(body);
} else {
console.log("Success: \n", body);
res.status(200).json(body_json);
}
});
});
// *************** POST DOC ***************************************
app.post('/postData', function (req, res) {
var request = require("request");
var httpHeaderOptions = {
accept: "application/json",
"content-type": "application/json",
apikey: req.headers.apikey
};
var restoptions = {
method: "POST",
url: req.headers.route,
headers: httpHeaderOptions,
body: req.body,
json: true
};
console.log("headers: " + JSON.stringify(req.headers));
console.log("POST DOC: \n", JSON.stringify(restoptions));
request(restoptions, function (error, response, body) {
if (typeof (body) == 'object' && Object.keys(body).length === 0) {
// unknown error, empty resposne
res.status(400).json(body);
} else {
console.log("body: " + JSON.stringify(body));
if (error) {
console.error("Failed: %s", error.message);
body = {
"error": error.message
};
res.status(400).json(body);
} else {
console.log("Success: \n", JSON.stringify(body));
res.status(200).json(body);
}
}
});
});
// *********************
app.post('/watsonAssistant', function (req, res) {
var request = require("request");
var reqURL = "https://hackathon-jps.eu-de.mybluemix.net/watsonAssistant";
console.log("URL: \n", reqURL);
console.log("POST Body: \n", JSON.stringify(req.body));
var httpHeaderOptions = {
accept: "application/json",
"content-type": "application/json",
};
var restoptions = {
method: "POST",
url: reqURL,
headers: httpHeaderOptions,
body: req.body,
json: true
};
console.log("send request \n");
request(restoptions, function (error, response, body) {
console.log("in request \n");
if (error) {
console.error("Failed: %s", error.message);
body = {
"error": error.message
};
res.status(400).json(body);
} else {
console.log("Success: \n", body[0]);
res.status(200).json(body[0]);
}
});
});
// Start the server
app.listen(port, function () {
console.log('simple forward server is running')
});
link to the code
This will be because whatever req.headers.route is set to, is not visible to the app when it is running in the cloud. Your first check should be on error. Your second check should be if body is not null, and an object instead you immediately JSON.parse body, which may be throwing a parsing exception.
i still learn, and trying to be learn. im looking for trying hard remote method on loopback 3 for push notification to specific user with onesignal.
any wrong in my code ?
because always :
Error: [ 'All included players are not subscribed' ]
My Case :
im using ionic 3 framework
loopback 3 (or latest)
2 User, (Customer & Seller)
Customer buying product from thread's seller.
If success to order, the seller will receive the notification.
and This is My code :
Ajiorder.observe('after save', function (ctx, next) {
console.log('Order', ctx.instance);
let postingModel = app.models.AjiPosting;
let userAuth = app.models.AjiUserAuth;
postingModel.find({
where:
{ id: ctx.instance.id }
}, function (err, success) {
console.log(success, 'SUKSES');
if (ctx.instance) {
let dataFilter = [];
dataFilter.push({
'field': 'tag',
'key': 'id',
'relation': '=',
'value': success[0].id
});
console.log(success[0].idSeller, 'ID TOT')
console.log(dataFilter, 'dataFilter');
let data = {
idSeller: ctx.instance.idSeller
}
console.log(data, 'Data');
userAuth.find({
where:
{ id: ctx.instance.idCustomer }
}, function (err, result) {
console.log(result, 'Data Personal');
let content = result[0].namaLengkap + ' ' + 'Order your product';
console.log(content, 'Nama Order');
console.log(ctx.instance.idSeller, 'My Dream', success[0].id);
if (ctx.instance.id != success[0].id) {
console.log('Spirit');
sendMessage(dataFilter, content, data);
}
})
}
next();
});
});
var sendMessage = function (device, message, data) {
var restKey = 'XXXXXXXXXXXXXXXXXX';
var appID = 'XXXXXXXXXXXXXXXXX';
request(
{
method: 'POST',
uri: 'https://onesignal.com/api/v1/notifications',
headers: {
'authorization': 'Basic ' + restKey,
'content-type': 'application/json'
},
json: true,
body: {
'app_id': appID,
'filters': device,
'data': data,
'contents': { en: message }
}
},
function (error, response, body) {
try {
if (!body.errors) {
console.log(body);
} else {
console.error('Error:', body.errors);
}
} catch (err) {
console.log(err);
}
}
)
}
};
and i got this error :
Error: [ 'All included players are not subscribed' ]
Picture : Picture of Console Log Here
any one can help me ?
sorry for my english too bad.
Greetings
Solved !
I'm Forget to add some code from onesignal. thanks
As per the question title, I am trying to post to facebook serverside with node.js
Unfortunately there is something wrong with how I am doing it...
I am getting the error
{ [Error: socket hang up] code: 'ECONNRESET' }
app.post('/post/:id?', function(req, res)
{
var id = req.route.params.id;
var token = tokens[id].token;
var path = '/' + id + '/feed?access_token=' + token;
var message = "server side post to facebook";
console.log("post.id = " + req.route.params.id);
var jsonobject = JSON.stringify(
{
'message' : message
});
var options = {
host: 'graph.facebook.com',
port: 443,
path: path,
method: 'post',
headers: {
'content-type': 'application/json',
'content-length': jsonobject.length()
}
};
var req = https.request(options, function(res) {
console.log("statuscode: ", res.statuscode);
console.log("headers: ", res.headers);
res.setencoding('utf8');
res.on('data', function(d) {
process.stdout.write(d);
});
res.on('end', function(){ // see http nodejs documentation to see end
console.log("finished posting message");
});
});
req.on('error', function(e) {
console.error(e);
});
req.write(jsonobject);
req.end();
});
I am not sure exactly what I did, but after lots of hacking it seems to work...
So for anyone who is interested:
app.post('/post/:id?', function(req, res)
{
var id = req.route.params.id;
var token = tokens[id].token;
var path = '/' + id + '/feed?access_token=' + token;
var strToPost = "server side post to facebook";
console.log("post.id = " + req.route.params.id);
var post_data = querystring.stringify({
'message' : 'testing server side post'
});
var options = {
host: 'graph.facebook.com',
port: 443,
path: path,
method: 'POST',
headers: {
'Content-Type' : 'application/x-www-form-urlencoded',
'Content-Length' : post_data.length
}
};
var req = https.request(options, function(res) {
console.log("statuscode: ", res.statuscode);
console.log("headers: ", res.headers);
res.setEncoding('utf8');
res.on('data', function(d) {
console.log("res.on data");
process.stdout.write(d);
});
res.on('end', function(){ // see http nodejs documentation to see end
console.log("\nfinished posting message");
});
});
req.on('error', function(e) {
console.log("\nProblem with facebook post request");
console.error(e);
});
req.write(post_data);
req.end();
});