Apex Class:

Public with sharing class SendemailController{
public String caseId {get;set;}

Public SendemailController(){
caseId = ApexPages.currentPage().getParameters().get(‘Id’);
}

Public Pagereference sendEmailFunction(){
Case getEmail = [SELECT Id, Contact.Email FROM Case WHERE id=:caseId];
if(getEmail.Contact.Email != null) {
String toaddress = getEmail.Contact.Email;
try {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {toaddress};
String[] ccAddresses = new String[] {‘test@gmail.com’};
mail.setToAddresses(toAddresses);
mail.setCcAddresses(ccAddresses);
mail.setReplyTo(toaddress);
mail.setSenderDisplayName(‘Name’);
mail.setSubject(‘Testing email through apex’);
mail.setBccSender(false);
mail.setUseSignature(true);
mail.setPlainTextBody(‘This is test email body. This mail is being sent from apex code’);
//mail.setHtmlBody(‘<b> This is HTML body </b>’ );

List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
for (Attachment a : [select Name, Body, BodyLength from Attachment where ParentId = :caseId]){
Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
efa.setFileName(a.Name);
efa.setBody(a.Body);
fileAttachments.add(efa);
//mail.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
}
mail.setFileAttachments(fileAttachments);

Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

} catch(Exception e) {}
}

PageReference reference = new PageReference(‘http://new-developer-edition.ap1.force.com/ThankYou?caseId=’+caseId);
reference.setRedirect(true);
return reference;
}

}

 

VI Page:

<apex:page controller=”SendemailController”>
<apex:form >
<script type=”text/javascript”>
function init() {
sendEmail();
}
if(window.addEventListener)
window.addEventListener(‘load’,init,true)
else
window.attachEvent(‘onload’,init)
</script>

<apex:actionFunction name=”sendEmail” action=”{!sendEmailFunction}”>
</apex:actionFunction>
</apex:form>
</apex:page>

 

(1283)

Written by 

I am Sakthivel Madesh, a certified Salesforce Developer & Administrator working on Salesforce Technology since 2011. I am currently working in IBM Austraila as Sr. Salesforce Developer. I have worked on multiple technologies Like PHP, Java, Salesforce, I am very passionate about Salesforce and to earn 10 Salesforce Certification. I love Trailhead for learning Salesforce Skill and Become a Trailhead Ranger too. I Love to Learn & Share my Salesforce knowledge to Salesforce Learners/Beginner using My Blog and Salesforce Community.

Leave a Reply