[SalesForce] Send email on Custom button click

I was able to implement: OnClick on Custom button to redirect to the Email template page with values filled-in using:

location.replace('/_ui/core/email/author/EmailAuthor?p2_lkid={!Contact.Id}&p3_lkid={!Case.Id}&retURL={!Case.Id}&template_id=00Xn0000000MYQyXXA&p26=noreply@arnoldjr.com');

But is there a way to implment:
OnClick –> Sends an email, gives me an alert message on Screen Email sent successfully and redirects back to the Case record detail page?

Best Answer

Try this code, behind the Custom button, this is perfectly working for me.

Note that, Only User, Contact, Lead, or Person objects are allowed for targetObjectId

Code

{!REQUIRESCRIPT("/soap/ajax/31.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/31.0/apex.js")}
var message = new sforce.SingleEmailMessage(); 

message.targetObjectId = "{!Contact.Id}";
message.toAddresses = "{!Contact.Email}";
message.templateId = "00Xq0000000HwSw"; 
message.whatId = "{!Case.Id}"; 

var result = sforce.connection.sendEmail([message]); 
if(result[0].success == 'true') 
{ 
    alert("Email sent successfully"); 
} else 
{ 
    alert("Sending failed"); 
} 
alert(result);

Refer Partner WSDL, to find the other attributes of SingleEmailMessage

<complexType name="SingleEmailMessage">
<complexContent>
<extension base="tns:Email">
<sequence>
<element name="bccAddresses" minOccurs="0" maxOccurs="25" type="xsd:string" nillable="true"/>
<element name="ccAddresses" minOccurs="0" maxOccurs="25" type="xsd:string" nillable="true"/>
<element name="charset" type="xsd:string" nillable="true"/>
<element name="documentAttachments" minOccurs="0" maxOccurs="unbounded" type="tns:ID"/>
<element name="entityAttachments" minOccurs="0" maxOccurs="unbounded" type="tns:ID"/>
<element name="fileAttachments" minOccurs="0" maxOccurs="unbounded" type="tns:EmailFileAttachment"/>
<element name="htmlBody" type="xsd:string" nillable="true"/>
<element name="inReplyTo" minOccurs="0" type="xsd:string" nillable="true"/>
<element name="optOutPolicy" type="tns:SendEmailOptOutPolicy" nillable="true"/>
<element name="orgWideEmailAddressId" minOccurs="0" maxOccurs="1" type="tns:ID" nillable="true"/>
<element name="plainTextBody" type="xsd:string" nillable="true"/>
<element name="references" minOccurs="0" type="xsd:string" nillable="true"/>
<element name="targetObjectId" type="tns:ID" nillable="true"/>
<element name="templateId" type="tns:ID" nillable="true"/>
<element name="toAddresses" minOccurs="0" maxOccurs="100" type="xsd:string" nillable="true"/>
<element name="treatBodiesAsTemplate" type="xsd:boolean" nillable="true"/>
<element name="treatTargetObjectAsRecipient" type="xsd:boolean" nillable="true"/>
<element name="whatId" type="tns:ID" nillable="true"/>
</sequence>
</extension>
</complexContent>
</complexType>
Related Topic