I can't send email with pdf using Amazon SDK JS, but send txt works fine? - amazon-ses

I'm trying to build a function to send email with pdf, I need to read the file from other server and then attach it to the email.
I have test it with txt and it works fine, but when I use pdf, it attach a file that cannot be open.
That's my code until now:
let dados = {
"para": "::EMAIL::",
"body": "Olá",
"assunto": "Teste",
"from": "::EMAIL::",
"anexo": "teste.pdf" // Name of the file I want to read from server
};
request.get("::URL_SERVER::" + dados.anexo, function (error, response, body) {
let anexo;
if (!error && response.statusCode == 200) {
anexo = body;
}
let ses_mail =
`From: 'AWS SES Attchament Configuration' <${dados.from}>
To: <${dados.para}>
Subject: ${dados.assunto}
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="NextPart"
--NextPart
Content-Type: text/html
${dados.body}
--NextPart
Content-Type: application/pdf; name="${dados.anexo}"
Content-Transfer-Encoding: base64
Content-Disposition:attachment
${anexo.toString("base64").replace(/([^\0]{76})/g, "$1\n")}
--NextPart`;
let params = {
RawMessage: {Data: ses_mail},
Source: `'AWS SES Attchament Configuration' <${dados.from}>`
};
let sendPromise = new AWS.SES({apiVersion: '2010-12-01'}).sendRawEmail(params).promise();
return sendPromise.then(
data => {
console.log(data);
return data;
}).catch(
err => {
console.error(err.message);
throw err;
});
});
It is possible to do it with axios? I only found how to download file on my research

I could do it, but I needed to change the lib I was using to sync-request.
My final code:
let anexo = null;
try {
anexo = request( "GET", "::URL::" + dados.anexo );
} catch (err) {
console.error(err, err.stack);
return criarResposta( 404, 'Anexo não encontrado' );
}
anexo = anexo.getBody();
//return criarResposta( 200, anexo.toString("base64") );
let ses_mail =
`From: 'AWS SES Attchament Configuration' <${dados.from}>
To: <${dados.para}>
Subject: ${dados.assunto}
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="NextPart"
--NextPart
Content-Type: text/html
${dados.body}
--NextPart
Content-Type: application/octet; name="arquivo.pdf"
Content-Transfer-Encoding: base64
Content-Disposition:attachment
${anexo.toString("base64")}
--NextPart`;
let params = {
RawMessage: {Data: ses_mail},
Source: `'AWS SES Attchament Configuration' <${dados.from}>`
};
sendPromise = new AWS.SES({apiVersion: '2010-12-01'}).sendRawEmail(params).promise();
try {
const data = await sendPromise;
console.log(data.MessageId);
return criarResposta( 200, 'OK' );
} catch (err) {
console.error(err, err.stack);
return criarResposta( 500, 'Erro interno' );
}

Related

Converting a docx Node.js buffer into pdf file

I am trying to convert the docx document from my node buffer into a pdf document using pdfmake. The pdf is generating but it has no content inside of it. I really don't know where that problem is coming from. I don't mind not using pdfmake, I'm up for anything that can solve the problem really.
`
exports.Resolution = functions.https.onCall(async (data, context) => {
const file_name = 'Resolution.docx';// this is the file saved in my firebase storage
const templateRef = await admin.storage().bucket()
.file(file_name);
const template_content = (await templateRef.download())[0];
const zip = new PizZip(template_content);
let doc;
try {
doc = new Docxtemplater(zip, { linebreaks: true });
} catch (error) {
// Catch compilation errors (errors caused by the compilation of the template : misplaced tags)
errorHandler(error);
}
doc.setData({
date: data.date,
investorName: data.investorName,
companyName: data.companyName,
regNo: data.regNo,
agreements: data.agreements,
governmentEntity: data.governmentEntity,
directors: data.directors,
equityStake: data.equityStake,
governmentEntityName: data.governmentEntityName,
fccp: data.fccp,
investorDirector:data.investorDirector,
equity: data.equity
});
try {
doc.render();
} catch (error) {
errorHandler(error);
}
const contentBuffer = doc.getZip().generate({ type: "nodebuffer" });
const nameofFile = 'Resolution Approving Transaction ' + data.investorName;
const printer = new PdfPrinter(fontss);
const chunks = [];
const pdfDoc = printer.createPdfKitDocument(contentBuffer);
pdfDoc.on('data', (chunk) => {
chunks.push(chunk);
});
pdfDoc.on('end', async () => {
const result = Buffer.concat(chunks);
function mail (){
const dest = context.auth.token.email;
const mailOptions = {
from: 'MPC <mypocketcounsel#gmail.com>',
to: dest,
cc:data.extraEmail,
subject: 'Resolution Approving Transaction',
text: 'Dear ' + data.name+ ',\n\nPlease find attached your Resolution Approving Transaction.\n\nThank you for using MPC Web. \n\n Best regards,\n\n The MPC Team.',
attachments: [
{
filename: nameofFile+'.docx',
content: contentBuffer
},
{
filename: nameofFile +'.pdf',
contentType: 'application/pdf',
content: result
}
]
};
// returning result
return transporter.sendMail(mailOptions);
}
return mail();
});
pdfDoc.on('error', (err) => {
return functions.logger.log('An error occured!');
});
pdfDoc.end();
});
`
This is the function that generates both the docx file and the pdf for me.

is there any better way to upload multiple large files on server in Flutter

I am trying to upload multiple files on server in flutter but they are taking to much time to upload.I am using Dio() for uploading..is any better way to upload multiple files on server in flutter.?
I am sending upload function.in which 10 files during upload takes more than 5 minutes
here is my code!
_upLoadFiles() async {
List <FileWithComment> uploadControls = preUpload();
var token = await _getToken();
print("Token: $token");
if (files) {
try {
final result = await InternetAddress.lookup("google.com");
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
FormData data = FormData.fromMap({
"jwt": token,
"comment": [],
"directory": widget.dName,
"directory_id": widget.folderId,
"case_id": widget.case_id,
"media_files": await _mediaFileList(),
});
await Dio()
.post(
"${MyFlutterApp.baseUrl}media_upload.php",
data: data,
onSendProgress: _setUploadProgress,
options: Options(
contentType: "multipart/form-data",
),
)
.then((res) => (res.data))
.then((d) => json.decode(d))
.then((res) => postUpload(res));
}
} on SocketException catch (_) {
_saveLocal(uploadControls);
} catch (e) {
if (e.toString().contains("Cannot retrieve length of file")) {
_showSnackBar("Cannot Upload File Try Again Later", Color(0xffDC0000), Colors.white);
}
}
} else {
print("${widget.dName}");
try {
final result = await InternetAddress.lookup("google.com");
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
FormData data = FormData.fromMap({
"jwt": token,
"directory": widget.dName,
"directory_id": widget.folderId,
"case_id": widget.case_id,
"comment": list.map((filewithcomment) => filewithcomment.comment).toList(),
"media_files": await _mediaFileList(),
"f_location": list.map((filewithcomment) => filewithcomment.location).toList(),
});
await Dio()
.post("${MyFlutterApp.baseUrl}media_upload.php",
data: data,
onSendProgress: _setUploadProgress,
options: Options(
contentType: "multipart/form-data",
))
.then((res) {
return res.data;
})
.then((d) => json.decode(d))
.then((res) => postUpload(res));
}
} on SocketException catch (_) {
_saveLocal(uploadControls);
} catch (e) {
print(e);
if (e.toString().contains("Cannot retrieve length of file")) {
_showSnackBar("Cannot Upload File Try Again Later", Color(0xffDC0000), Colors.white);
}
}
}
}
This is mediafileList()..May be there is issue in these lines of code
Future<List<MultipartFile>> _mediaFileList() async {
Completer complete = Completer<List<MultipartFile>>();
List<MultipartFile> filesList = [];
for (int index = 0; index < list.length; index++) {
if (list[index].file is File) {
var file = list[index].file;
filesList.add(await MultipartFile.fromFile(file.path, filename: file.path.split('/').last));
}
if (list[index].file is String) {
var file = File(list[index].file);
filesList.add(await MultipartFile.fromFile(
file.path, filename: file.path.split('/').last));
}
if (index == list.length - 1) complete.complete(filesList);
}
return complete.future;
}

CKEDITOR File Upload Bad Request 400 Error

I am using ckEditor with the file browser, filemanager plugin in it. What i am trying to achieve when i configure the CKeditor I am able to browse the file in a certain folder .. but when i try to upload the file through it I am getting an error of 400 Bad Request may be there is something which I need to do ?
Following is my code
[HttpPost]
CKEDITOR.replace('content_editor',{
customConfig: '/assets/back/dist/plugins/ckeditor/config.js',
"imageBrowser_listUrl" : "/webmaster/files/browser"
});
CKEDITOR.on('fileUploadRequest', function (evt) {
var fileLoader = evt.data.fileLoader,
formData = new FormData(),
xhr = fileLoader.xhr;
xhr.open( 'PUT', fileLoader.uploadUrl, true );
formData.append( 'upload', fileLoader.file, fileLoader.fileName );
fileLoader.xhr.send( formData );
// Prevented the default behavior.
evt.stop();
} );
Request Handler C# ASP.NET CORE 3.1
public async Task<IActionResult> UploadFromEditor([FromForm]IFormFile upload)
{
if (upload.Length <= 0) return null;
if (!upload.IsImage())
{
var NotImageMessage = "please choose a picture";
dynamic NotImage = JsonConvert.DeserializeObject("{ 'uploaded': 0, 'error': { 'message': \"" + NotImageMessage + "\"}}");
return Json(NotImage);
}
var fileName = Guid.NewGuid() + Path.GetExtension(upload.FileName).ToLower();
Image image = Image.FromStream(upload.OpenReadStream());
int width = image.Width;
int height = image.Height;
if ((width > 750) || (height > 500))
{
var DimensionErrorMessage = "Custom Message for error";
dynamic stuff = JsonConvert.DeserializeObject("{ 'uploaded': 0, 'error': { 'message': \"" + DimensionErrorMessage + "\"}}");
return Json(stuff);
}
if (upload.Length > 500 * 1024)
{
var LengthErrorMessage = "Custom Message for error";
dynamic stuff = JsonConvert.DeserializeObject("{ 'uploaded': 0, 'error': { 'message': \"" + LengthErrorMessage + "\"}}");
return Json(stuff);
}
var path = Path.Combine(
Directory.GetCurrentDirectory(), "wwwroot/uploads/images/conten_images",
fileName);
using (var stream = new FileStream(path, FileMode.Create))
{
upload.CopyTo(stream);
}
var url = $"{"/uploads/images/CKEditorImages/"}{fileName}";
var successMessage = "image is uploaded successfully";
dynamic success = await Task.Run(() => JsonConvert.DeserializeObject("{ 'uploaded': 1,'fileName': \"" + fileName + "\",'url': \"" + url + "\", 'error': { 'message': \"" + successMessage + "\"}}"));
return Json(success);
}
Extra Plugins code :
CKEDITOR.editorConfig = function( config ) {
config.filebrowserBrowseUrl = '/assets/back/dist/ckeditor/plugins/imagebrowser/browser/browser.html'
config.filebrowserUploadUrl = '/webmaster/files/UploadFromEditor';
config.extraPlugins = 'filetools';
config.extraPlugins = 'uploadimage';
config.extraPlugins = 'popup';
config.extraPlugins = 'imagebrowser';
config.filebrowserUploadMethod = 'xhr';
};
Please help me out here
here are the headers :
XHRPOSThttps://localhost:5001/webmaster/files/UploadFromEditor
[HTTP/2 400 Bad Request 73ms]
POST
https://localhost:5001/webmaster/files/UploadFromEditor
Status400
Bad Request
VersionHTTP/2
Transferred85.50 KB (0 B size)
content-length
0
date
Tue, 03 Nov 2020 09:13:50 GMT
server
Kestrel
X-Firefox-Spdy
h2
Accept
*/*
Accept-Encoding
gzip, deflate, br
Accept-Language
en-US,en;q=0.5
Connection
keep-alive
Content-Length
86268
Content-Type
multipart/form-data; boundary=---------------------------1063707225330149515660008029
Cookie
.AspNetCore.Session=CfDJ8ERqQf6e11lCnNAhOo0wjyavEQJqEJ7gsv1MXMI4QwPk9Px8mznruNuZcxnmuYGnGjs1GtOWQI4DVCXYKd%2FRbNNo62%2FtopzHy%2FxaW87rvNE13QikL84JT0m32Ie1LWSZR3AkxYAE5p4U7TEpN5FccezCSMDeUR9geLW3lSjFIJD4; .AspNetCore.Antiforgery.J7MIrShXchg=CfDJ8ERqQf6e11lCnNAhOo0wjyYadzIaShP7Nt-bl6orx5lTMtnVoGxw8noimjE32qvhp_f96p2Hx4_zK8hzdRIz12615ZdyisBTz6X9HPA39cgIvRTjmWmrWNcLlm4S2MvPAQrG9hofg1ANinWAOwKIyXc; ckCsrfToken=8qZ4KEfRjaBWRmI6coRoRbJrZd8DgYG18gAz86eN; .AspNetCore.Antiforgery.XfkU3LYWHPY=CfDJ8NfGIpF9PVtNgLP3wXt3ZoscmmPZ8ZskVSbYiI69p4lPZYB3mt9mFEqRuOV0Ajfi2f8NNbjcyEHtfta7RlEHTBhXdRfPonXD1sN2EIS2BvcjZCrN8sJXN4UMo_JlolirVt3VIcCTm-wGAtIzGq0150w
Host
localhost:5001
Origin
https://localhost:5001
Referer
https://localhost:5001/webmaster/News/Create
TE
Trailers
User-Agent
Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0
X-Requested-With
XMLHttpRequest
Cookie “.AspNetCore.Antiforgery.XfkU3LYWHPY” will be soon treated as cross-site cookie against “https://localhost:5001/webmaster/files/UploadFromEditor” because the scheme does not match. UploadFromEditor
Source map error: Error: request failed with status 404
Resource URL: https://localhost:5001/assets/back/dist/bootstrap/js/bootstrap.min.js
Source Map URL: bootstrap.min.js.map
Based on the details about your test request, it seems that you configured and enabled antiforgery token validation. If JavaScript client not set/include the token in request, which would cause 400 Bad Request error.
To fix it, as I mentioned in comment, we can apply IgnoreAntiforgeryToken Attribute to action method UploadFromEditor to skip antiforgery token validation.
Or set the token in request header to make the request can pass antiforgery token validation.
https://learn.microsoft.com/en-us/aspnet/core/security/anti-request-forgery?view=aspnetcore-3.1#javascript

Uploaded image on parse.com gives 403 error

I am trying to upload image to parse.com using REST API, and associating to an object as shown in docs
I am getting the fileUrl from phonegap / appgyver-supersonic camera api.
The Image is uploaded successfully and also associated successfully to the "receipt" object but accessing the url gives 403 error.
How do I access the URL and view the uploaded image, I get a white page (with broken image icon) and 403 error.
File :
http://files.parsetfss.com/68087456-8a5a-403a-820f-13912d2c0911/tfss-5d0edbdb-730b-4cd6-a44f-f0ce1e2ab120-pic.jpg
My receipt class has public write/read access.
Here is my code :
$scope.send = function(fileURL, mimeType){
function win(r) {
$scope.textvar = r;
var response = JSON.parse(r.response);
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
var req = {
method: 'POST',
url: 'https://api.parse.com/1/classes/receipt',
headers: {
'X-Parse-Application-Id':'XXXXXXXXXXXXX',
'X-Parse-REST-API-Key':'XXXXXXXXXXXXXXXX',
"Content-Type": "application/json"
},
data: {"name": "user_receipts",
"images": {
"name": response.name,
"__type" : "File"
}
}
}
$http(req).success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log("image association success ");
console.log(data);
console.log(headers);
console.log(status);
console.log(config);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
function fail(error) {
console.log("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
console.log("upload error http-code " + error.http_status);
}
var uri = encodeURI("https://api.parse.com/1/files/pic.jpg");
var options = new FileUploadOptions();
options.fileKey="data-binary";
options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1);
options.mimeType=mimeType;
var headers = {"X-Parse-Application-Id": "XXXXXXXXXXXXXXXXX",
"X-Parse-REST-API-Key":"XXXXXXXXXXXXXXXX",
"Content-Type":"image/jpeg"};
options.headers = headers;
var ft = new FileTransfer();
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
console.log("length : "+progressEvent.loaded/progressEvent.total);
} else {
console.log("loaded : "+progressEvent.loaded);
}
};
ft.upload(fileURL, uri, win, fail, options);
};
I have wasted 5 days on this already, Please Help.
I am no expert in either appgyver / phonegap or parse.com

How can I use a payload instead of form-data for log4javascript

I am bound to the restrictions of my webservice: It expects a json-payload!
So, doing something like
var ajaxAppender = new log4javascript.AjaxAppender("clientLogger");
var jsonLayout = new log4javascript.JsonLayout();
ajaxAppender.setLayout(jsonLayout);
log.addAppender(ajaxAppender);
won't work, as it creates two keys in the forms-collection (data and layout).
How can I, with built-in options, get a json-payload?
I've created a JsonAppender
function JsonAppender(url) {
var isSupported = true;
var successCallback = function(data, textStatus, jqXHR) { return; };
if (!url) {
isSupported = false;
}
this.setSuccessCallback = function(successCallbackParam) {
successCallback = successCallbackParam;
};
this.append = function (loggingEvent) {
if (!isSupported) {
return;
}
$.post(url, {
'logger': loggingEvent.logger.name,
'timestamp': loggingEvent.timeStampInMilliseconds,
'level': loggingEvent.level.name,
'url': window.location.href,
'message': loggingEvent.getCombinedMessages(),
'exception': loggingEvent.getThrowableStrRep()
}, successCallback, 'json');
};
}
JsonAppender.prototype = new log4javascript.Appender();
JsonAppender.prototype.toString = function() {
return 'JsonAppender';
};
log4javascript.JsonAppender = JsonAppender;
used like so
var logger = log4javascript.getLogger('clientLogger');
var jsonAppender = new JsonAppender(url);
logger.addAppender(jsonAppender);
According to log4javascript's change log, with version 1.4.5, there is no longer the need to write a custom appender, if the details sent by Log4Javascript suffice.
1.4.5 (20/2/2013)
- Changed AjaxAppender to send raw data rather than URL-encoded form data when
content-type is not "application/x-www-form-urlencoded"
https://github.com/DECK36/log4javascript/blob/master/changelog.txt
Simply adding the 'Content-Type' header to the AjaxAppender and setting it to 'application/json' is enough
ajaxAppender.addHeader("Content-Type", "application/json;charset=utf-8");
A quick test using fiddler shows that log4javascipt sends a collection of objects. Here's a sample of the payload:
[{
"logger": "myLogger",
"timestamp": 1441881152618,
"level": "DEBUG",
"url": "http://localhost:5117/Test.Html",
"message": "Testing message"
}]