Send email via AWS Lambda where body is UTF8 - aws-sdk

I can't figure out how to get my email browser (I'm using mail.yahoo.com at the moment) to decode UTF-8 data sent via my AWS Lambda function. The email is sent and received fine, but the UTF-8 data shows up in quoted-printable format.
The headers should be:
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable
... but as you can see, I can only specify UTF-8 via "Charset," from the AWS JavaScript SDK, which isn't working.
// create email params
var params = {
Destination: {
CcAddresses: [],
ToAddresses: ['dummy#email.co']
},
Message: {
Body: {
Html: {
Charset: "UTF-8",
Data: message
},
Text: {
Charset: "UTF-8",
Data: message
}
},
Subject: {
Charset: 'UTF-8',
Data: 'New email from ' + domain_name
}
},
Source: 'aws#' + domain_name,
ReplyToAddresses: ['dummy#email.co']
};
So the problem is the browser doesn't appear to be receiving the proper content-type headers, which I believe is a function of some variable I'm missing.

Related

api call for image and use it for base64

Due to a site cross-issue on Safari reason regarding CORS, I cannot use URL directly to frontend
what I am doing is making an API call to the URL and converting it to base64 sending to frontend and using it there passing in
Unfortunately, It's not working as the image shows is broken, I suspect that it's due to some unknown reason.
https://scontent.cdninstagram.com/v/t51.29350-15/325642177_505094921747710_9035707955179438711_n.webp?stp=dst-jpg&_nc_cat=107&ccb=1-7&_nc_sid=8ae9d6&_nc_ohc=hcMVLqiH044AX_O3sip&_nc_ht=scontent.cdninstagram.com&edm=AEoDcc0EAAAA&oh=00_AfDfXVcdc658NDViC2RvQDUbeZuvOhOl5M-xliFO9XfbdQ&oe=63C5998C
this is the image URL I am making API call
const config = {
method: "get",
url,
responseType: "arraybuffer",
headers: {},
};
const datares = await axios(config);
let base64;
base64 = Buffer.from(datares?.data).toString('base64');
if (datares?.status !== 200) {
return res.status(500).json({
success: false,
msg: datares?.data?.message || "Internal server error",
});
}
// base64 with img according to the url
const accpbase64 = `data:image/jpeg;base64,${base64}`;
res.status(200).json({
success: true,
data: accpbase64,
msg: "base64 retrieved successfully",
});
This is the API call response and below is the header of response
{
'x-storage-error-category': 'dfs:none;hs_p:200:HS_ESUCCESS',
'last-modified': 'Fri, 13 Jan 2023 14:04:31 GMT',
'x-haystack-needlechecksum': '2479215415',
'x-needle-checksum': '3312581816',
'content-type': 'image/jpeg',
'content-digest': 'adler32=3360421242',
'timing-allow-origin': '*',
'cross-origin-resource-policy': 'cross-origin',
'access-control-allow-origin': '*',
'cache-control': 'max-age=1209600, no-transform',
'accept-ranges': 'bytes',
'x-fb-trip-id': '2141700578',
date: 'Fri, 13 Jan 2023 17:46:19 GMT',
'alt-svc': 'h3=":443"; ma=86400',
connection: 'close',
'content-length': '112923'
}
https://codesandbox.io/s/unruffled-farrell-3jb93m?file=/src/App.js
here's example response of base64 using as in tag
Can someone help me here with this?
Your value in accpbase64 works fine. You just need to use that value in the src of your image.
See demo with base64 of image you provided, https://codesandbox.io/s/determined-noyce-u0j0g1

Parse FormData object in nest controller

I have a nest controller which accepts the following DTO, One of the parameters should be a buffer which is read from file
It suppose to read bin file
interface LoadFileRequest {
targetIp: string;
fileBuffer: Buffer;
user: User;
}
interface User {
username: string;
password: string;
}
#Controller('loader')
export class KeyLoaderController {
#Post('load')
async load(#Body() body: LoadFileRequest, #Req() request) {
console.log(body);
console.log(request);
}
}
My code for testing the controller:
import axios from "axios";
import fs from "fs";
import FormData from "form-data";
let headersList = {
Accept: "*/*",
};
let formdata = new FormData();
formdata.append("targetIP", "10.10.1.145");
formdata.append(
"user",
JSON.stringify({
username: "user",
password: "auth",
})
);
formdata.append("fileBuffer", fs.createReadStream("test.bin"));
let bodyContent = formdata;
const url = "http://localhost:3000/loader/load";
let reqOptions = {
url,
method: "POST",
headers: headersList,
data: { bodyContent },
};
axios.request(reqOptions).then(function (response) {
console.log(response.data);
});
At the controller this is the request body i get
{
bodyContent: {
_overheadLength: 380,
_valueLength: 48,
_valuesToMeasure: [ [Object] ],
writable: false,
readable: true,
dataSize: 0,
maxDataSize: 2097152,
pauseStreams: true,
_released: false,
_streams: [
'----------------------------092840744027446269037569\r\n' +
'Content-Disposition: form-data; name="targetIP"\r\n' +
'\r\n',
'10.10.1.145',
null,
'----------------------------092840744027446269037569\r\n' +
'Content-Disposition: form-data; name="user"\r\n' +
'\r\n',
'{"username":"user","password":"auth"}',
null,
'----------------------------092840744027446269037569\r\n' +
'Content-Disposition: form-data; name="fileBuffer"; filename="test.bin"\r\n' +
'Content-Type: application/octet-stream\r\n' +
'\r\n',
[Object],
null
],
_currentStream: null,
_insideLoop: false,
_pendingNext: false,
_boundary: '--------------------------092840744027446269037569'
}
}
How can i get the body in the form of object with only the attrbutes of the DTO?
Eventually i got a method which recived the same type of object and i want to call it like this:
#Controller('loader')
export class KeyLoaderController {
#Post('load')
async load(#Body() body: LoadFileRequest, #Req() request) {
return await loadFile(body);
}
}
EDIT:
I changed the code a bit and now if i send the request from VS code thunder client it works fine(sort of):
#Controller('loader')
export class KeyLoaderController {
#Post('load')
#UseInterceptors(FileInterceptor('fileBuffer'))
async load(#Body() body, #UploadedFile() file) {
console.log(body);
console.log(file);
}
}
When I send this way (The code on the right is the generated code by the extension, Which does not act the same way when I use it):
This is the body and file I get:
[Object: null prototype] {
targetIP: '10.10.1.145',
user: '{ "username": "user", "password": "0123456789"}'
}
{
fieldname: 'fileBuffer',
originalname: 'test.bin',
encoding: '7bit',
mimetype: 'application/octet-stream',
buffer: <Buffer ... ... 119 more bytes>, size: 169
}
But when i take the code i generated in VS code thunder client (which is at axios request in this post) I still get the body like before (again, as mention in the post)
If you're sending a multipart/form-data request, you need a form data body parser installed on the server. You can either use the FileInterceptor (or one of the derivatives of it), or bind multer as a middleware for the entire server. This will allow for the parsing of multipart/form-data requests.
In your axios call, remove the brackets around bodyContent so it becomes data: bodyContent. You aren't sending an object of form data you are just sending formdata itself

Node.js Request GET returning raw data instead of JSON [duplicate]

This question already has answers here:
Encoding issue with requesting JSON from StackOverflow API
(2 answers)
Closed 5 years ago.
I have a particularly interesting issue, So I am trying to use Stackoverflow Search/Advanced API to query stackoverflow to get questions. I have tried it using PostMan and its returning JSON but in my Node.js application it is returning me raw data.
exports.GetQuestions = function(query,requestify)
{
var request = require("request");
var options = { method: 'GET',
url: 'https://api.stackexchange.com/2.2/search/advanced',
qs:
{ order: 'desc',
sort: 'activity',
site: 'stackoverflow',
q: 'Error: Can\'t find Python executable
"C:\\Users\\harig\\AppData\\Local\\Programs\\Python\\Python36\\python.EXE",
you can set the PYTHON env variable' },
headers:
{ 'postman-token': 'b0b78842-94cd-a0b9-39cc-0e099136900c',
'cache-control': 'no-cache',
'Accept': 'application/json' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
}`
I generated the code for the request using postman itself, I tried it on different API and the same code is working fine.
I need help in figuring out how to get JSON as response.
Here is the response:
cache-control: private
content-type: application/json; charset=utf-8
content-encoding: gzip
access-control-allow-origin: *
access-control-allow-methods: GET, POST
access-control-allow-credentials: false
x-content-type-options: nosniff
date: Sun, 21 Jan 2018 16:12:19 GMT
connection: close
content-length: 4780
Here is a sample of data returned:
���������U����"�z�f%��-??ӵm��N�|�f&��fે�n�.""��DX�Ƀ�P��J�(�p�U�Q�N47 �1�M�.�|]�t5agA��0�rc �g�3��}
+�Y�q/�pL��M�RƜGwt�B��ڍ�#���9(>s��ʀ6�#�w���e/��Mu�ʮ��9,�ML|
�s9�a���ߑW�r�[����ߗa�������a�~6��>ͦ����u�3���a�|P-�ᣖ�S'
�
򄾤�#v�D�PXM�i��ȹ��O�{2N�s��?
����ڝ���O_������/ ���ř��M3��w�ܾ����g"�� ���$�(%"�r#S�Px3��;?4^}�܏�n�S�f7U[���g7�
a�cȩbҷ�Oq����X,8w�5Szp�P�y���rg�<�������m�;�u���|��aXJ��!��~X�bK�#�b5���,)W+����)������+n[cl()�����lC>
okoSHcY��c\�TW0ƊLM
��ݒ���oN9دhV���t��rj��
*�cPޝ�~l���E�́Ѳ�o3Dp�Eus侫��L��R�n��i�`+����DF���h $~377s=��W��xP��#�CAN�1�T�Ub0c$�e����S���&���B�}�~��Q�������m��m�������a�|���sL�Y;z8��T}�j~�]޽}���El�����]|��B�����*nt�^�,�����
k'
7�J�IO�i�d�m�4"�N���DZ��1䞦'�[�&�j���~�6�).G��v=��gn��x4�6nh�����V��o�)���^ಧ�2����['6����z� �#�/���J���j+vD�xƍ)N����qC[C���U��Z|�����vh���_��>�gd�9��v���.��i�U�zJ��,�*J��RBt�s��iӮo��f�^A3��$�"7�N��!�l�b,"��96�#�������C���.��a�52'a�v�U��9��v]�l�~kΎ��ԌG�藊<9�eN;]t��n�k?;cu� L�u}�t���q;৯��=�����Y��ZK������AL.�L
The response you received is gzip compressed as shown by content-encoding: gzip.
Set gzip:true in your options.
var options = { method: 'GET',
gzip: true,
url: 'https://api.stackexchange.com/2.2/search/advanced',
qs:
{ order: 'desc',
sort: 'activity',
site: 'stackoverflow',
q: 'Error: Can\'t find Python executable
"C:\\Users\\harig\\AppData\\Local\\Programs\\Python\\Python36\\python.EXE",
you can set the PYTHON env variable' },
headers:
{ 'postman-token': 'b0b78842-94cd-a0b9-39cc-0e099136900c',
'cache-control': 'no-cache',
'Accept': 'application/json' } };

Using Linkedin API with google apps script?

aloha all,
Im create a integration with linkedin and google apps script, for post in company page.
All is good, in terms of oauth2, i have the tokens, but the problem is the body request, look:
var payload = {"visibility": {"code": "anyone"},"comment": "Testing a full company share!","content": {"submitted-­url": "https://www.google.com","title": "Test Share with Content","description": "content description","submitted‐image-­url": "https://www.wired.com/wp-content/uploads/2015/09/google-logo.jpg"}};
var headers = {Authorization': 'Bearer ' + Service.getAccessToken()};
var options = {method:'post',headers:headers,payload:payload,muteHttpExceptions:true};
var response = UrlFetchApp.fetch("https://api.linkedin.com/v1/companies/2414183/shares?format=json", options);
THE REQUES IS GOOD, BECAUSE I USE APIGEE FOR TEST MY JSON REQUEST. THIS IS THE RESPONSE OF THE SERVER:
[16-12-12 22:38:13:411 EST] {
"errorCode": 0,
"message": "Couldn't parse share document: error: Unexpected element: CDATA",
"requestId": "XNZ80U0LCX",
"status": 400,
"timestamp": 1481600293335
}
IN SEVERAL FORUMS SAY THAT THE HEARDER I SHOUD PUT:
'Content-Type': 'application/json', 'x-li-format': 'json'
BUT WHEN PUT THIS CODE ON HEADER THE ERROR OF SERVER IS:
[16-12-12 22:40:00:344 EST] {
"errorCode": 0,
"message": "Couldn't parse Json body: Unexpected character ('v' (code 118)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')\n at [Source: java.io.StringReader#c3576e8; line: 1, column: 2]",
"requestId": "YQFPJKZTMC",
"status": 400,
"timestamp": 1481600400231
}
THANKS ALL
For payload you need to provide valid JSON e.g.:
var payload = JSON.stringify(object):
Not:
var payload = object;
I'd also add the content type to the headers, setting it to application/json:
var options = {
'contentType': 'application/json',
'payload': JSON.stringify(payload)
};
UrlFetchApp.fetch('https://www.example.com', options);
One change... Per the Linkedin developer docs:
If you opt to provide a JSON-formatted body, make sure your HTTP request includes the following headers:
Content-Type: application/json
x-li-format: json
https://developer.linkedin.com/docs/share-on-linkedin

UrlFetchApp upload file multipart/form-data in Google Apps Script

I need to upload files to a 3rd party service. The files are created on Google Drive, and I get the blob-data for it.
I want to create a multipart request which now looks like this when I do the UrlFetchApp Post.
This is the payload as string. I have some code that generates the payload. Getting it properly formatted is not the problem, it's the format it is supposed to be.
-----------------0.13accb4c42d338
Content-Disposition: form-data; name="source"; filename="Zzapps.jpg"
Content-Type: application/octet-stream
[[[IMAGE DATA HERE -- OMITTED FOR BREVITY]]]
-----------------0.13accb4c42d338
Content-Disposition: form-data; name="filename"
Zzapps.jpg
-----------------0.13accb4c42d338--
This is the piece of code that does the UrlFetchApp command.
var authHeaders = {
Authorization: 'OAuth2 '+access_token
}
var params = {
accept: "application/json",
method: 'POST',
payload: payload,
contentType: 'multipart/form-data; boundary='+boundaryKey,
headers: authHeaders,
ContentLength: payload.length,
muteHttpExceptions: true
}
var resx = UrlFetchApp.fetch(url, params);
The recieving party gives an error (missing source). I am not sure if my multipart-post is okay in the first place, I do not find any testing URL's to check if I do a proper upload.
How could I send blob-data as a multipart upload the proper way?
And now I use blob.getDataAsString() <-- is this correct ?
If you're building the payload string yourself, you want to do blob.getBytes(), not blob.getDataAsString().
However, there's an easier way. Rather than building the payload string yourself, you can just set a javascript object as the payload, and UrlFetchApp will automatically generate the appropriate payload string, select the correct content-type, boundary, and most of the other options. Just use the "name" attribute of the HTML form's input fields as your object keys. For files, use blobs as the key's values.
function sendReportToSteve() {
var url = "https://example.com/stevedore.html";
var form = {
date : new Date(),
subject : "Happy birthday!",
comment : "quakehashprismkeepkick",
attachment1 : DriveApp.getFileById("sH1proy0lradArgravha9ikE").getBlob(),
attachment2 : DriveApp.getFileById("traCetRacErI3hplVnkFax").getBlob()
};
uploadFile(url,form);
}
function uploadFile(url,form) {
var options = {
method : "POST",
payload : form
};
var request = UrlFetchApp.getRequest(url,options); // (OPTIONAL) generate the request so you
console.info("Request payload: " + request.payload); // can examine it (useful for debugging)
var response = UrlFetchApp.fetch(url,options);
console.info("Response body: " + response.getContentText());
}