+ Start a Discussion
kumarcrm bingikumarcrm bingi 

Sending Email with Attachment using Apex

public class CER_Reimbursement_SendemailController {
public String caseId {get;set;}
public list<CER_Expense_Reimbursement__c> CER_Expense_Reimbursement {get;set;}

Public CER_Reimbursement_SendemailController(){
caseId = ApexPages.currentPage().getParameters().get('Id');
system.debug('case id->'+caseId );
}

Public Pagereference sendEmailFunction(){
CER_Expense_Reimbursement__c[] getEmail = [SELECT Id, EER_EmployeeName__r.email FROM CER_Expense_Reimbursement__c WHERE id=:caseId];
if (getEmail.size() > 0){
    if(getEmail[0].EER_EmployeeName__r.email != null) {
String toaddress = getEmail[0].EER_EmployeeName__r.email;

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {toaddress};
String[] ccAddresses = new String[] {'sfdcsrini@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 });

}
}

PageReference reference = new PageReference('Url'+caseId);
reference.setRedirect(true);
return reference;
}
}
visual force 
<apex:page controller="CER_Reimbursement_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>
User-added image
 
Raj VakatiRaj Vakati
What is the issue here ?/ 

Please refer this link 

https://howtodoitinsalesforce.blogspot.com/2016/12/send-emails-with-attachment-from-your.html
https://www.greytrix.com/blogs/salesforce/2017/03/29/send-an-email-with-attachment-from-salesforce/
http://sfdcsrini.blogspot.com/2014/06/sending-email-with-attachment-using.html
https://www.salesforcetutorial.com/sending-email-with-attached-document-by-using-apex/