Send pdf file as mail attachment using mailgun api from angularjs - javascript

I have created an angularjs app for invoice generation.
Here is the Demo.
The user can type in the details and can download the invoice in pdf format.
I did the pdf generation with html2canvas and pdfMake as shown here.
Now I want to implement a feature to mail this generated pdf to the given mail id.
I don't want to use any backend for this app.
So far I tried mailgun. But I couldn't send the mail with attachment. Actually I am not sure whether I can pass the pdf file from angular to the api.
my email function is,
$scope.send = function() {
console.log("here")
$http({
"method": "POST",
"url": "https://api.mailgun.net/v3/sandbox7106da0b6ed8488bb186182ed794df0f.mailgun.org/messages",
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic " + mailgunApiKey
},
data: "from=" + $scope.to + "&to=" + $scope.to + "&subject=" + $scope.subject + "&html=" + "some message" ,
}).then(function(success) {
console.log("SUCCESS " + JSON.stringify(success));
}, function(error) {
console.log("ERROR " + JSON.stringify(error));
});
}
The mail is getting sent.
I dont know how to add my pdf as attachment.
Here is the function where I create pdf using pdfMake,
$scope.pdf= function() {
html2canvas(document.getElementById('invoice'), {
onrendered: function (canvas) {
var data = ca
nvas.toDataURL();
var docDefinition = {
content: [{
image: data,
width: 580,
}],
pageSize: 'A4',
pageMargins: [ 20, 0, 10, 20 ],
};
pdfMake.createPdf(docDefinition).download("invoice.pdf");
}
});
};
Please Help me to send the mail with pdf attachment.

Related

Upload to vimeo with tus-js-client

I’m new to tus and I’m using tus-js-client. I’m following the example in this link https://github.com/tus/tus-js-client/blob/master/docs/usage.md#example-upload-to-vimeo.
I was able to successfully upload a video on Vimeo but I would like to set the title/name and description in advance. And also the optional onSuccess function is not returning anything. I would like to get the video details that I’ve uploaded successfully like the clipid.
Are these things something possible to do on tus-js-client? Below is my code for reference.
function UploadVideoTusJs(uploadUrl, videoFile) {
var upload = new tus.Upload(videoFile.files[0], {
uploadUrl: uploadUrl,
metadata: {
name: videoFile.files[0].name, // not working
description: "Test", // not working
},
onError: function (error) {
console.log("Failed because: " + error);
},
onProgress: function (bytesUploaded, bytesTotal) {
var percentage = (bytesUploaded / bytesTotal * 100).toFixed(2)
console.log(bytesUploaded, bytesTotal, percentage + "%")
},
onSuccess: function (data) {
console.log(data); //returns undefined
console.log("Download %s from %s", upload.file.name, upload.url);
},
onAfterResponse: function (req, res) {
var url = req.getURL()
var value = res.getHeader("X-My-Header")
console.log(`Request for ${url} responded with ${value}`)
}
});
// Start the upload by default
upload.start();
}
-- Dan
Vimeo's implementation of tus is a bit different as the "creation" step is done using the Vimeo API, not using tus. If you want to provide metadata like name or description, that should be provided with the initial API request, which should look something like this:
var settings = {
"url": "https://api.vimeo.com/me/videos",
"method": "POST",
"timeout": 0,
"headers": {
"Accept": "application/vnd.vimeo.*+json;version=3.4",
"Content-Type": "application/json",
"Authorization": "Bearer TOKEN"
},
"data": JSON.stringify({"upload":{"approach":"tus","size":666666666},"name":"name","description":"description"}),
};
$.ajax(settings).done(function (response) {
console.log(response);
});
Hope this points you in the right direction!

Unable to get dominant colour of image using Microsoft's Computer Vision

I've been stuck on this problem for a while.
I'm trying to get the dominant colour of an image using Microsoft's Computer Vision service.
An extract of my code is below:
import {VisualFeatureTypes} from "#azure/cognitiveservices-computervision/esm/models";
...
let visualFeatures: VisualFeatureTypes[] = ['Color'];
const caption = (await computerVisionClient.analyzeImageInStream(describeURL, visualFeatures));
Doing a console.log(caption) returns the following JSON object:
{
"categories": [
{
"name": "others_",
"score": 0.15625
}
],
"requestId": "5a24115f-8095-4a77-8aa9-2d719dce99e6",
"metadata": {
"width": 500,
"height": 500,
"format": "Jpeg"
}
}
The Computer Vision service definitely works, because if I change the method from analyzeImageInStream to describeImageInStream and remove, then I get the appropriate response.
For testing, I've been using this image here, and using Computer Vision's Demo. The demo returns colour information, but my API call does not.
Any help would be greatly appreciated.
Based on this doc, you should put the params in your url. https://learn.microsoft.com/en-us/azure/cognitive-services/computer-vision/quickstarts/javascript-analyze
const urlBase = "https://....cognitiveservices.azure.com/vision/v3.0/analyze";
var params = {
"visualFeatures": "Categories,Description,Color",
"details": "",
"language": "en",
};
$.ajax({
url: uriBase + "?" + $.param(params),
// Request headers.
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader(
"Ocp-Apim-Subscription-Key", subscriptionKey);
},
type: "POST",
// Request body.
data: '{"url": ' + '"' + sourceImageUrl + '"}',
}) .done(function(data) {
// Show formatted JSON on webpage.
callYourFunction(data);
})

Pdf is rendered with white pages

I am sending from my back-end pdf which works fine. I tried to open it in the browser directly (localhost:8843/documents/2/?access_token=123)
But when I am opening it with JS, it loads only white pages without content. Eventhough the size of the pdf is the same, but it is empty...
I tried to open those pdf even in my back end server and it works ok... so there must be some error at front end.
const getPdf = (id) => {
$.ajax({
url: proxy + "documents/" + id,
headers: {
'Authorization': 'bearer ' + localStorage.access_token},
type: "GET",
success: function(data) {
var blob=new Blob([data]);
var link=document.querySelector(".pdf-link");
link.href=window.URL.createObjectURL(blob);
link.download="document.pdf";
},
error: function(error){
alert(error);
}
});
}

Send attachment via SendGrid using Parse Cloud Code Module

I am trying to send an attachment to my email using SendGrid, in this case the attachment is of type NSData. Is there a way to send an attachment using SendGrid without having an URL or that image saved in Parse? I want to go from phone straight to email w/ attachment.
Currently the email is sending successfully, just do not have an image/attachment. Thanks in advance!
Parse.Cloud.define("sendBookRequestEmail", function(request, response) {
var Buffer = require('buffer').Buffer;
var buffer1 = new Buffer(request.params.image);
var b3 = buffer1.toString('base64');
var SendGrid = require("sendgrid");
SendGrid.initialize("username", "password");
SendGrid.sendEmail({
to: "email",
from: request.params.email,
subject: "Requesting book",
text: "Title: " + request.params.title + "\r\n" + "Author: " + request.params.author + "\r\n" + "ISBN: " + request.params.isbn + "\r\n" + "I want to: " + request.params.bookrequest + "\r\n" + "Notes: " + request.params.notes,
attachments: [request.params.image]
}, {
success: function(httpResponse) {
response.success("success");
console.log(httpResponse);
},
error: function(httpResponse) {
console.error(httpResponse);
}
});
});
The object that you were passing to the sendMail call does not have the right structure. Try something like this:
sendEmail({
to: "email",
from: request.params.email,
subject: "subject",
text: "text",
attachments: [{
content: b3, // 'Some base 64 encoded attachment content'
filename: 'some-attachment.txt',
type: 'plain/text',
disposition: 'attachment',
contentId: 'mytext'
}
],
});

Create File with Google Drive Api v3 (javascript)

I want to create a file with content using Google Drive API v3. I have authenticated via OAuth and have the Drive API loaded. Statements like the following work (but produce a file without content):
gapi.client.drive.files.create({
"name": "settings",
}).execute();
Unfortunately I cannot figure out how to create a file that has a content. I cannot find a JavaScript example using Drive API v3. Are there some special parameters that I need to pass?
For simplicity, assume that I have a String like '{"name":"test"}' that is in JSON format that should be the content of the created file.
Unfortunately, I have not found an answer using only the google drive api, instead I followed Gerardo's comment and used the google request api. Below is a function that uploads a file to google drive.
var createFileWithJSONContent = function(name,data,callback) {
const boundary = '-------314159265358979323846';
const delimiter = "\r\n--" + boundary + "\r\n";
const close_delim = "\r\n--" + boundary + "--";
const contentType = 'application/json';
var metadata = {
'name': name,
'mimeType': contentType
};
var multipartRequestBody =
delimiter +
'Content-Type: application/json\r\n\r\n' +
JSON.stringify(metadata) +
delimiter +
'Content-Type: ' + contentType + '\r\n\r\n' +
data +
close_delim;
var request = gapi.client.request({
'path': '/upload/drive/v3/files',
'method': 'POST',
'params': {'uploadType': 'multipart'},
'headers': {
'Content-Type': 'multipart/related; boundary="' + boundary + '"'
},
'body': multipartRequestBody});
if (!callback) {
callback = function(file) {
console.log(file)
};
}
request.execute(callback);
}
here is the solution with gapi.client.drive,
var parentId = '';//some parentId of a folder under which to create the new folder
var fileMetadata = {
'name' : 'New Folder',
'mimeType' : 'application/vnd.google-apps.folder',
'parents': [parentId]
};
gapi.client.drive.files.create({
resource: fileMetadata,
}).then(function(response) {
switch(response.status){
case 200:
var file = response.result;
console.log('Created Folder Id: ', file.id);
break;
default:
console.log('Error creating the folder, '+response);
break;
}
});
you'll need to connect/authorise with either of the following scopes
https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.file
EDIT: it is possible to create google files (doc, sheets and so on) by changing the mimeType from application/vnd.google-apps.folder to one of the supported google mime types. HOWEVER, as of now it not possible to upload any content into created files.
To upload files, use the solution provided by #Geminus. Note you can upload a text file or a csv file and set its content type to google doc or google sheets respectively, and google will attempt to convert it. I have tested this for text -> doc and it works.
Using gapi.client.drive, it is not possible to upload file content. You can only upload metadata.
Instead it is recommended to work directly with the Google REST API. This solution uses a FormData object to build the multipart form body, which simplifies the implementation, and gapi.auth.getToken() to retrieve the required access token. The solution also works with Google shared drives:
var fileContent = "sample text"; // fileContent can be text, or an Uint8Array, etc.
var file = new Blob([fileContent], {type: "text/plain"});
var metadata = {
"name": "yourFilename",
"mimeType": "text/plain",
"parents": ["folder id or 'root'"], // Google Drive folder id
};
var accessToken = gapi.auth.getToken().access_token;
var form = new FormData();
form.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' }));
form.append('file', file);
fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&supportsAllDrives=true", {
method: 'POST',
headers: new Headers({ 'Authorization': 'Bearer ' + accessToken }),
body: form,
}).then((res) => {
return res.json();
}).then(function(val) {
console.log(val);
});
this works fine usin v3:
var fileMetadata = {
'name' : 'MaxBarrass',
'mimeType' : 'application/vnd.google-apps.folder'
};
gapi.client.drive.files.create({
resource: fileMetadata,
fields: 'id'
}).execute(function(resp, raw_resp) {
console.log('Folder Id: ', resp.id);
});
/* Now to create a new file */
function insertNewFile(folderId)
{
var content = " ";
var FolderId = "";
var contentArray = new Array(content.length);
for (var i = 0; i < contentArray.length; i++)
{
contentArray[i] = content.charCodeAt(i);
}
var byteArray = new Uint8Array(contentArray);
var blob = new Blob([byteArray], {type: 'text/plain'});
insertFile(blob, fileInserted, folderId);
}
function fileInserted(d)
{
setPercent("100");
var FI = FolderId;
if(FI !== myRootFolderId)
{
insertFileIntoFolder(FI, d.id);
removeFileFromFolder(d.parents[0].id,d.id);
}
openFile(d.id);
}
function insertFileIntoFolder(folderId, fileId)
{
var body = {'id': folderId};
var request = gapi.client.drive.parents.insert({
'fileId': fileId,
'resource': body });
request.execute(function(resp) { });
}
Source: https://gist.github.com/mkaminsky11/8624150

Categories

Resources