[SalesForce] Send Email from Custom Button

I have a Visualforce page and I would like to create a custom button that sends an email template to the user's Manager (via the Manager field on the user record) and VP (a custom lookup field on my custom object). I tried to do this via a URL hack, but all that does is pull up the pre-populated template. I want the email to be sent without the user even seeing the template. Is this possible to do right in the VF page without a controller, perhaps with Javascript? And if so, is there any code examples?

Current Button:

<a
role="button"
class="btn" 
style="text-decoration:none;background:#FFFF00;"
href = "/_ui/core/email/author/EmailAuthor?rtype=003&
        p3_lkid={!DS.Id}&
        retURL=%2F{!DS.Id}&
        p5={!$User.Email}&
        p24={!$User.Manager_Email__c},{!DS.BD_Manager__r.email}&
        template_id=00X37000000kzHl",
        target = "_self">
<b>Manager Review</b>
</a>

Best Answer

Yes you can do with Salesforce AJAX Toolkit. You can write something like this in your JavaScript. You can update the SendMail function with all the required parametes and call from the onclick action of the button.

<apex:page >
    <script type="text/javascript">
        var __sfdcSessionId = '{!GETSESSIONID()}';
    </script>
    <script src="../../soap/ajax/34.0/connection.js" type="text/javascript"></script>
    <script type="text/javascript">
        function SendMail() {
            try {
                sforce.connection.sessionId = "{!$Api.Session_ID}";
                var message = new sforce.SingleEmailMessage();
                message.replyTo = "xxxx@gmail.com";
                message.targetObjectId = "xxxxxxxxxxxxxxxxx";
                message.templateId = "xxxxxxxxxxxxxxxxx";
                message.saveAsActivity = false;
                message.plainTextBody = "this test went through ajax";
                var result = sforce.connection.sendEmail([message]);
                if(result[0].success == 'true') {
                    alert("Mail sent successfully");
                } else {
                    alert("I had a booboo.");
                }
            }catch(e) { 
                alert("Error Occurred: \n\n" + (e.message||e));
            }
        }
  </script>  
</apex:page>
Related Topic