Send attachment via SendGrid using Parse Cloud Code Module - javascript

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'
}
],
});

Related

Calling Web Service .asmx from JavaScript using AJAX

I have implemented a pop-up in an asp.net web app which allows the user to select something and an email template is generated. After completing all the required fields, the user sends the email by the click of a button.
This button calls a JavaScript function where I gather all the user input data like from, to, subject, body and want to send this data to a web service I have created which will send the mail.
I didn't want to use mailto, so I went with web service.
The problem is that I can't send the data:
$.ajax({
type: 'POST',
url: "Services/MailService.asmx/SendMail",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: { 'loginName': "'" + loginName + "'", 'fromAddress': "'" + fromAddress + "'", 'toAddress': "'" + toAddress + "'", 'mailSubject': "'" + mailSubject + "'", 'mailBody': "'" + mailBody + "'"},
success: function ()
{
alert("The email was sent successfully!");
},
error: function(data)
{
alert("An error occurred while trying to send the email. " + data.responseText);
}
});
I know that what I inserted in the data property is wrong. I have tried the following, (one at a time):
data: JSON.stringify({ 'loginName': loginName, 'fromAddress': fromAddress, 'toAddress': toAddress, 'mailSubject': mailSubject, 'mailBody': mailBody }),
data: { 'loginName': loginName, 'fromAddress': fromAddress, 'toAddress': toAddress, 'mailSubject': mailSubject, 'mailBody': mailBody },
data: { loginName: loginName, fromAddress: fromAddress, toAddress: toAddress, mailSubject: mailSubject, mailBody: mailBody },
data: "{ 'loginName': '" + loginName + "', 'fromAddress': '" + fromAddress + "', 'toAddress': '" + toAddress + "', 'maliSubject': '" + mailSubject + "', 'mailBody': '" + mailBody + "' }",
All these options give me the following errors:
An error occurred while trying to send the email. {"Message":"Invalid web service call, missing value for parameter: \u0027mailBbody\u0027.","StackTrace":" at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters)\r\n at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}
or
An error occurred while trying to send the email. {"Message":"Invalid JSON primitive: loginName.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}
I don't understand what I'm doing wrong.
The web service looks like this:
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public void SendMail(string loginName, string fromAddress, string toAddress, string mailSubject, string mailBody)
{
MailMessage mailMsg = new MailMessage(fromAddress, toAddress);
mailMsg.Subject = mailSubject;
mailMsg.Body = mailBody;
string pathToCreate = "~/Upload/" + loginName + "/";
if (Directory.Exists(Server.MapPath(pathToCreate)))
{
if (Directory.GetFiles(Server.MapPath(pathToCreate)).Length > 0)
{
string[] attachedFiles = Directory.GetFiles(Server.MapPath(pathToCreate));
foreach (string a in attachedFiles)
{
Attachment data = new Attachment(a);
mailMsg.Attachments.Add(data);
}
}
}
SmtpClient smtp = new SmtpClient();
smtp.Send(mailMsg);
}
}
What could I do to solve this issue?
I was able to successfully send the data by using:
data: '{loginName:' + JSON.stringify(loginName) + ', fromAddress:' + JSON.stringify(fromAddress) + ', toAddress:' + JSON.stringify(toAddress) + ', mailSubject:' + JSON.stringify(mailSubject) + ', mailBody:' + JSON.stringify(mailBody) + '}',
I don't know if this is the right way but it's working.

Send pdf file as mail attachment using mailgun api from angularjs

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.

How to use $http post data to ssl enabled server in angularjs

$http.post(myurl, myreq).success(function(apiReply) {
if (! checkApiResponse(apiReply)){
console.log("failed to run action with error: " + apiReply.retcode + " " + apiReply.retbody)
return false
} else {
callback(apiReply)
}
}).error(function(data, status) {
var errmsg = "handle api request failed with status: "
errmsg += status + ", error response: " + data
console.log(errmsg)
ons.notification.alert({
//title: "错误",
//message: '连接服务器失败',
title: "提示",
message: "请检查您的网络环境",
buttonLabel: ['确认']
});
});
}
here is my way to post data ,when using http url,it works fine,but doesn't work when i use https url, what should i do?

Facebook story posting issue

I am setting up for posting story on facebook but I am getting following alert:
You, or this app's Open Graph Test User, must have published this action at least once.
I am getting id in the response but when I am clicking on that I am redirecting to "Page not found".
Here is my code :
FB.api(
'me/objects/appnamespace:objecttype',
'post',
{
object :{
app_id: myappId,
objectype: myurl,
title: "Sample Organization",
image: mylogo,
description: ""
}
},
function(response) {
if (!response) {
alert('Error occurred.');
} else if (response.error) {
document.getElementById('result').innerHTML =
'Error: ' + response.error.message;
} else {
document.getElementById('result').innerHTML =
'<a href=\"https://www.facebook.com/me/activity/' +
response.id + '\">' +
'Story created. ID is ' +
response.id + '</a>';
}
}
);

(#3) App must be on whitelist facebook

I'm trying to post a messsage to a wall using FB.api
My perms are: 'email, read_stream, publish_stream' and my code is:
FB.getLoginStatus(function(response){
if(response.session) {
var accessToken = response.session.access_token;
var tokenUrl = "https://graph.facebook.com/me/feed?access_token=" + accessToken + "&callback=?";
var shareUserId = document.getElementById("shareHidden").value;
var shareTxtAreaMsg = document.getElementById("shareTxtArea").value;
console.log("friends user Id: " + shareUserId + " & " + "message: " + shareTxtAreaMsg);
var data = {
message: "shareTxtAreaMsg",
display: 'iframe',
caption: "Caption",
name: "Name",
picture: 'http://someDomain.com/Dev/img/share-force-wall-img.jpg',
link: "http://www.facebook.com/pages/someapp/XXXXXXXXXXX?sk=app_XXXXXXXXXXXXXX", // Go here if user click the picture
description: "Description field",
actions: [{ name: 'action_links text!', link: 'some link' }],
}
console.log(accessToken);
FB.api(tokenUrl, 'post', data, function(response){
if (response)
{
//console.log(response);
if (response.error)
{
console.log(response.error.message);
}
else
{
if (response.id)
console.log("Posted as post_id "+response.id);
else if (response.post_id)
console.log("Posted as post_id "+response.post_id);
else
console.log("Unknown Error");
}
}
});
}
});
When when try to post the message I'm getting a "(#3) App must be on whitelist" returned. Why is this happening?
Try FB.api('/me/feed'... instead of tokenUrl because FB.api will automatically add the full url prefix.

Categories

Resources