parse.com cloud code can't send email via mandrillapp - parse-platform
I'm trying to send an email via parse.com via mandrill. The examples are very easy to follow, but I'm getting a strange error.
here is my code:
Parse.Cloud.afterSave("ip", function(request) {
var IPLogger_config = require('cloud/mandrillapp_config.js');
var Mandrill = require('mandrill');
Mandrill.initialize(IPLogger_config.mandrillAppKey);
console.log('within afterSave for ip');
console.log(request.object.id);
var ip = Parse.Object.extend("ip");
var query = new Parse.Query(ip);
query.descending("createdAt");
query.limit(2); // limit to at most 2 results
query.find({
success: function(results){
console.log('success query');
console.log('got ' + results.length + ' results');
var newestIp = results[0];
var olderIp = results[1];
if (newestIp.get('ip') == olderIp.get('ip') ) {
// the newest ip and the older one are equal, do nothing.
console.log('No ip change');
} else
{
console.log('ip change!');
console.log(Mandrill.initialize);
console.log(Mandrill.sendEmail);
Mandrill.sendEmail({
message: {
text: "The IP of your server has changed! The new ip is: " + newestIp.get('ip') ,
subject: "The IP of your server has changed!",
from_email: "parse#cloudcode.com",
from_name: "IPLogger",
to: [
{
email: IPLogger_config.your_email,
name: IPLogger_config.your_name
}
]
},
async: true
},{
success: function(httpResponse) {
console.log(httpResponse);
response.success("Email sent!");
},
error: function(httpResponse) {
console.error(httpResponse);
response.error("Uh oh, something went wrong");
}
});
}
},
error: function (error){
console.log('no success for query');
console.error("Got an error " + error.code + " : " + error.message);
}
});
});
my mandrillapp_config.js looks like this:
var IPLogger_config = {};
IPLogger_config.mandrillAppKey = "xxx";
IPLogger_config.your_email = 'myemail#bla.com';
IPLogger_config.your_name = 'myName';
The mandrillAppKey is correctly set. I double checked that. Sending email from mandrill website also works. I just created a new account and did no other settings on the mandrill site.
I'm getting this error: "code":-1,"name":"ValidationError","message":"You must specify a key value". In https://www.parse.com/questions/sometimes-getting-mandrill-you-must-specify-a-key-value-error-when-sending-email is written that the header might be wrong, but as you can see on my log, the "Content-Type":"application/json; charset=utf-8" is set correctly.
I2014-06-09T22:34:20.601Z] {
"uuid":"fbb215c4-1d2a-e2da-23fc-a838bd6bf217",
"status":500,
"headers":{
"Access-Control-Allow-Credentials":"false",
"Access-Control-Allow-Headers":"Content-Type",
"Access-Control-Allow-Methods":"POST, GET, OPTIONS",
"Access-Control-Allow-Origin":"*",
"Connection":"close",
"Content-Encoding":"gzip",
"Content-Type":"application/json; charset=utf-8",
"Date":"Mon, 09 Jun 2014 22:34:20 GMT",
"Server":"nginx/1.6.0",
"Vary":"Accept-Encoding",
"X-Powered-By":"PHP/5.3.10-1ubuntu3.11"
},
"text":"{\"status\":\"error\",\"code\":-1,\"name\":\"ValidationError\",\"message\":\"You must specify a key value\"}",
"data":{"status":"error","code":-1,"name":"ValidationError","message":"You must specify a key value"},
"buffer":{"0":123,"1":34,"2":115,"3":116,"4":97,"5":116,"6":117,"7":115,"8":34,"9":58,"10":34,"11":101,"12":114,"13":114,"14":111,"15":114,"16":34,"17":44,"18":34,"19":99,"20":111,"21":100,"22":101,"23":34,"24":58,"25":45,"26":49,"27":44,"28":34,"29":110,"30":97,"31":109,"32":101,"33":34,"34":58,"35":34,"36":86,"37":97,"38":108,"39":105,"40":100,"41":97,"42":116,"43":105,"44":111,"45":110,"46":69,"47":114,"48":114,"49":111,"50":114,"51":34,"52":44,"53":34,"54":109,"55":101,"56":115,"57":115,"58":97,"59":103,"60":101,"61":34,"62":58,"63":34,"64":89,"65":111,"66":117,"67":32,"68":109,"69":117,"70":115,"71":116,"72":32,"73":115,"74":112,"75":101,"76":99,"77":105,"78":102,"79":121,"80":32,"81":97,"82":32,"83":107,"84":101,"85":121,"86":32,"87":118,"88":97,"89":108,"90":117,"91":101,"92":34,"93":125,"length":94,
"parent":{"0":123,"1":34,"2":115,"3":116,"4":97,"5":116,"6":117,"7":115,"8":34,"9":58,"10":34,"11":101,"12":114,"13":114,"14":111,"15":114,"16":34,"17":44,"18":34,"19":99,"20":111,"21":100,"22":101,"23":34,"24":58,"25":45,"26":49,"27":44,"28":34,"29":110,"30":97,"31":109,"32":101,"33":34,"34":58,"35":34,"36":86,"37":97,"38":108,"39":105,"40":100,"41":97,"42":116,"43":105,"44":111,"45":110,"46":69,"47":114,"48":114,"49":111,"50":114,"51":34,"52":44,"53":34,"54":109,"55":101,"56":115,"57":115,"58":97,"59":103,"60":101,"61":34,"62":58,"63":34,"64":89,"65":111,"66":117,"67":32,"68":109,"69":117,"70":115,"71":116,"72":32,"73":115,"74":112,"75":101,"76":99,"77":105,"78":102,"79":121,"80":32,"81":97,"82":32,"83":107,"84":101,"85":121,"86":32,"87":118,"88":97,"89":108,"90":117,"91":101,"92":34,"93":125,"length":94},"offset":0},"cookies":{}}
Where can be the problem? any ideas how to get it running?
thank you very much!
I finally found the problem. There was en error in the config script.
it need to look like this:
var IPLogger_config = {};
IPLogger_config.mandrillAppKey = "xxx";
IPLogger_config.your_email = 'myemail#bla.com';
IPLogger_config.your_name = 'myName';
exports.IPLogger_config = IPLogger_config;
in the main.jsfile, the resources of the config file need to be called like this:
var config = require('cloud/mandrillapp_config.js');
Mandrill.initialize(config.IPLogger_config.mandrillAppKey);
and now it works fine.
Related
Mandrill with parse server not working on heroku migration
I have migrate app from parse.com to heroku with mLab and everything works fine except cloud code. I am using Mandrill for sending email from parse cloud code which is not working with heroku Here is what I have done so far: Installed mandrill ~0.1.0 into parse-server-example and push the code to heroku app Put the cloud code into '/cloud/main.js' Called the function from iOS app which respond error as: [Error]: Invalid function. (Code: 141, Version: 1.13.0). Here is my code script: Parse.Cloud.define("sendMail", function(request, response) { var Mandrill = require('mandrill'); Mandrill.initialize('xxxxxx-xxxxx'); Mandrill.sendEmail({ message: { text: "ffff", subject: "hello", from_email: "xxxxx#gmail.com", from_name: "pqr", to: [ { email: "xxxxxxxxxx#gmail.com", name: "trump" } ] }, async: true },{ success: function(httpResponse) { console.log(httpResponse); response.success("Email sent!"); }, error: function(httpResponse) { console.error(httpResponse); response.error("Uh oh, something went wrong"); } }); }); But after calling 'sendMail' function I am getting this error: [Error]: Invalid function. (Code: 141, Version: 1.13.0). ================================== MailGun ========================== Parse.Cloud.define('hello', function(req, res) { var api_key = 'key-xxxxxxxxxxxxxx'; var domain = 'smtp.mailgun.org'; var mailgun = require('mailgun-js')({apiKey: api_key, domain: domain}); var data = { from: 'xxxxxxxald#gmail.com', to: 'xxxxx8#gmail.com', subject: 'Hello', text: 'Testing some Mailgun awesomness!' }; mailgun.messages().send(data, function (error, body) { console.log(body); }); //res.success(req.params.name); });
I had a similar problem with sendgrid, but I finally find a way around the problem. I think this steps may help you, Miss some brackets or some code separator? ( try rewritting the entire code in the main.js ) The app is actually running? ( when you type "heroku open" in the terminal you get the default message? ) - if not check step 1. If the previous are not working, rollback to a safe build and Add the add-ons in the heroku dashboard instead of installing them yourself, then download the git and do any changes to git and then push.
Below I have pasted from cloud code main.js code that is working using Mandrill on heroku parse application to send password recovery e-mail. in cloud code main.js: var mandrill_key = process.env.MANDRILL_KEY; var Mandrill = require('mandrill-api/mandrill'); var mandrill_client = new Mandrill.Mandrill(mandrill_key); { success: function(gameScore) { //alert('New object created with objectId: ' + gameScore.id); mandrill_client.messages.send( { message: { html: "<p>Hello " + firstUser.get('fullname') + ",</p><p>We received your request to reset your password.</p><p>Your user name is <strong>" + firstUser.get('username') + "</strong>. Please click here to create a new password. This link will expire in one hour after this mail was sent</p><p>If you need additional help, just let us know.</p><p>SampleCompany Support<br>customerservice#example.com</p><p>Copyright Sample Company, Inc. 2014-2017</p>", subject: "Sample Company Name account recovery", from_email: "customerservice#example.com", from_name: "Sample Company Name", to: [ { email: firstUser.get('email'), name: firstUser.get('fullname') } ] }, async: true }, //Success function(httpResponse) { console.log(httpResponse); //alert("Email sent!"); }, //Failure function(httpResponse) { console.error(httpResponse); //alert("Uh oh, something went wrong"); }); }, error: function(gameScore, error) { console.error(error.message); //alert('Failed to create new object, with error code: ' + error.message); }, useMasterKey: true })
Saving or Creating a Parse File in Parse Cloud code
I am trying to create a Parse cloud code function that would run a query and then put the results of the query in csv file and finally using the mailgun plugin send it out to a receipient. Unfortunately I cannot figure out how to create a Parse File in cloud code. Suggestions? Parse.cloud.define("exportDataViaEmail", function(request, response){ var query = new Parse.Query("Diaper"); var today = new Date(); var startTime = new Date(today - 1000 * 60 * 60 * 24 * (7*52+1)); query.lessThan("logCreationDate", today); query.greaterThan("logCreationDate", startTime); query.find({ success: { //TODO I want store this in a Parse File but how? }, error :{ } }); }) /* * Send email via mailgun */ Parse.Cloud.define("sendEmail", function(request, response){ Mailgun.sendEmail({ to: "myemail#gmail.com", from: "hello#example.com", subject: "Hello From example App", text: "Using Parse and Mailgun is great!" }, { success: function(httpResponse) { console.log(httpResponse); response.success("Email sent!"); }, error: function(httpResponse) { console.error(httpResponse); response.error("Uh oh, something went wrong"); } }); })
Using files in cloud code is easy and is thoroughly documented in the Parse Javascript Guide It's as simple as var file = new Parse.File("myfile.txt", bytes);
CORS + sendAjax + authentication
I am using casperjs and have run more 1000 test runs. I was using sendAjax function to fetch json objects from couchdb and it was working without any issue. Yes I do have --web-security in my grunt file and using phantomjs with linux mint 13 64 bit. I can access the data manually by log in to couchdb interface and use the url to fetch the records from the database. I am unable to fetch the data from couchdb using the script below. var url = 'http://worksite.com:5984/draft/_design/WidgetData/_view/by_rootIdforTest?include_docs=true&startkey="52210def794e1e7a8dd8e74b8b0ab5a6"&endkey="52210def794e1e7a8dd8e74b8b0ab5a6"' var jsonObject = casper.evaluate(function(url) { try { return JSON.parse(__utils__.sendAJAX(url, 'GET', null, false)); } catch (e) {} }, { url: url }); return jsonObject; Modified script and added authentication credentials but request is not being authorized var url = 'http://worksite.com:5984/draft/_design/WidgetData/_view/by_rootIdforTest?include_docs=true&startkey="52210def794e1e7a8dd8e74b8b0ab5a6"&endkey="52210def794e1e7a8dd8e74b8b0ab5a6"' var jsonObject = casper.evaluate(function(url) { try { return JSON.parse(__utils__.sendAJAX(url, 'GET', { "name": "username", "password", "mypassword" }, false)); } catch (e) {} }, { url: url }); return jsonObject;
Parse.com: Retrieving object by objectId does not work. Why? It is very simple query
I got an error with message "101 Object not found." The below code is just copy from the official guide. And I changed the class name and the objectId. I know this is very simple query but I don't know why? Help me how to debug in this case... This code is in cloud code. I set up "applicationId" and "masterKey" in global.json. Thanks.. require('cloud/app.js'); Parse.Cloud.define("sample", function(request, response) { var GameScore = Parse.Object.extend("Item"); var query = new Parse.Query(GameScore); query.get("XXXXXX", { success: function(gameScore) { }, error: function(object, error) { console.error("error: " + error.code + " " + error.message); } }); });
I tend to use the promise method and I'd possibly rewrite it like this... Parse.Cloud.define("sample", function(request, response) { var query = new Parse.Query("Item"); // put this in as a debug message. console.log("Just checking I'm here!"); query.get("XXXXXX").then (function(item) { response.success(item); }, function(error) { console.error("error: " + error.code + " " + error.message); response.error(error); }); }); But it should work as it is. Odd. Are you sure the error message is coming from your code? Try adding a log before it. EDIT It seems that permissions were not set properly on your item object. With iOS you can specify a default ACL for objects at create time. You can also create a custom ACL object and pass it to the object when saving it.
Parse Cloud Code afterSave not working
Hey I'm using Parse as my backend and I love it but I have a problem with the afterSave hook. Here is the Code I'm using: Parse.Cloud.afterSave ("JGZwoelf",function (request) { Parse.Push.send({ //Selecting the Channel channels: [ request.object.get('JGZwoelfPush') ], data: { //Selecting the Key inside the Class alert: request.object.get('AusfallInfo') } }, { success: function () { //Push was send successfully }, error: function (error) { //Handle error throw "Got an error" + error.code + " : " + error.message; } }); }); Every time the logs console is telling me: Result: Uncaught Got an error112 : Missing channel name. I just don't understand what is wrong! It must be in that JavaScript code. If I enter the push notification manually everything works fine :/ Edit: The part Parse.Push.send should look like this: Parse.Push.send ({ //Selecting the already existing Push Channel channels: ["JGAchtPush"], //This has to be the name of your push channel!! data: { //Selecting the Key inside the Class alert: request.object.get ("AusfallInfo") } }, { success: function () { //Push was sent successfully //nothing was loged }, error: function (error) { throw "Got and error" + error.code + " : " + error.message; } }); The channel name needs to be something like ["exampleChannel"]. Thanks in advance for any given help :)
The first argument to afterSave should be a class name, not an objectId.
following is for new folks (like me), it is the exact same code in original question, plus a few more comments, plus the correction from accepted answer. purpose is to show example of what few pieces of code need changing for this to work in your parse cloud code. thank you Constantin Jacob and bklimt. Parse.Cloud.afterSave ("UserVideoMessage",function (request) { // name of my parse class is "UserVideoMessage" Parse.Push.send ({ //Selecting the already existing Push Channel channels: ["admin"], //This has to be the name of your push channel!! data: { //Selecting the Key inside the Class, this will be the content of the push notification alert: request.object.get ("from") } }, { success: function () { //Push was sent successfully //nothing was loged }, error: function (error) { throw "Got and error" + error.code + " : " + error.message; } }); });