[SalesForce] Custom Button to Send an email using email template

I have created a custom button on Opportunity. The custom button has following javascript code. When the user clicks on the button the email should be sent.I find no errors in the code. But I am not able to send any emails.

{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")}
(function() {
sforce.connection.sessionId = "{!$Api.Session_ID}";
var message = new sforce.SingleEmailMessage();
message.replyTo = "varunreddypenna@gmail.com,varunrp@okstate.edu";
message.targetObjectId = "{!Opportunity.Id}";
message.templateId = "00Xj0000000J8sI";
var result = sforce.connection.sendEmail([message]);
  if(result[0].success) {
     alert("I sent the email as you requested, master.");
  } else {
     alert("I had a booboo.");
  }
}());

Best Answer

I ran this code and result is not quite what you think.

If you alert the whole result object, you get this:

{errors:{message:'Only Users, Contact, Lead or Person objects are allowed for targetObjectId : a0SK000000FtD7J.', statusCode:'INVALID_TYPE_FOR_OPERATION', targetObjectId:null, }, success:'false', }

Your code needs to look like this to actually work:

{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")}
(function() {
sforce.connection.sessionId = "{!$Api.Session_ID}";
var message = new sforce.SingleEmailMessage();
message.replyTo = "rapsac@gmail.com";
message.targetObjectId = "005K0000002butj";
message.templateId = "00XK0000000QsbW";
message.saveAsActivity = false;
var result = sforce.connection.sendEmail([message]);
  if(result[0].success == 'true') {
     alert("I sent the email as you requested, master.");
  } else {
     alert("I had a booboo.");
  }
alert(result);
}());

There were several other errors too - the key is to output the whole error in an alert so you can debug it.

As you can see, the targetObjectId is the user that the email is going to, not the object that the template refers to.

Also, saveAsActivity needs to be false to send to an internal user.

This is probably going to take quite a bit of work to get going, but hopefully you are now on the right track.

Related Topic