function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
rmranjith8881.3927046400771116E12rmranjith8881.3927046400771116E12 

Test class for Custom Send an Email Button !!!

Hi EveryOne,

I have a Extensions on Oppportunity, which sends the Email with two Visualforce Pdf file attachments.
I need to write a test class for it,
As of now, My test coverage is 8%.
Please find my Code below.

Extension Code:
 
//Send email with Multiple attachments, and before sending edit template
public class SendEmail {

    public Account acc;
    public String body { get; set; }    
    Product_EmailTemplates__c template;//Custom settings to read the template, which template to send
    public Opportunity opp { get; set;}
    public String subject { get; set; }
    public String htmlBody {get; set;}
    

    // Create a constructor that populates the Opportunity object
    public SendEmail(ApexPages.StandardController controller) {        
        opp = [Select Id, Name, Email__c, Amount, Contact_Name__c, Account.PersonContactId, Account.id, Product__r.Name, Account.Name, StageName, Tax_Amount__c, Total_after_Tax__c, 
               payment_1_Amount__c, Payment_2_Amount__c, Payment_3_Amount__c, Payment_1_Before_Tax__c, Payment_2_Before_Tax__c, Payment_3_Before_Tax__c, Payment_1_Tax_Amount__c, 
               Payment_2_Tax_Amount__c, Payment_3_Tax_Amount__c, Potential_Number__c,Branch_Name__c, Branch_Name__r.Name, Branch_Name__r.Address_1__c, Branch_Name__r.Address_2__c, Branch_Name__r.City__c, 
               Branch_Name__r.Country__c, Branch_Name__r.Main_Phone_1__c, Branch_Name__r.Main_Phone_2__c, Branch_Name__r.Main_Phone_3__c, Branch_Name__r.Region__c, Branch_Name__r.State__c, 
               Branch_Name__r.Zip_Postal_Code__c, Product__r.Product_Type__c, Admin_Fee__c, Payment_1_plus_Admin_Fee__c
                    from Opportunity where Id = :ApexPages.currentPage().getParameters().get('id')];
              
        EmailTemplate emailTemplate = [SELECT Id, Subject, HtmlValue, Body FROM EmailTemplate WHERE Id = :getTemplateId(opp.Product__r.Name, opp.Product__r.Product_Type__c)];
    
        htmlBody = emailTemplate.HtmlValue;
        subject = emailTemplate.subject;
    }
    
    //Send the email with two attachments
    public PageReference send() {
        // Define the email
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
        
        //Send email if Branch not equals to Saudi Arabia and Product type is Standard
        if(opp.Branch_Name__r.Name != 'Saudi Arabia' && opp.Product__r.Product_Type__c == 'Standard'){
            // Reference the attachment page and pass in the Opportunity ID
            PageReference pdf1 =  Page.CCLPdf;//CCLPdf is a Visualforce page
            pdf1.getParameters().put('id',opp.id); 
            pdf1.setRedirect(true);
    
            // Take the PDF content
            Blob b1 = pdf1.getContentAsPDF();
            
            PageReference pdf2 =  Page.ProformaInvoicePdf;//ProformaInvoicePdf is a Visualforce page
            pdf2.getParameters().put('id',opp.id); 
            pdf2.setRedirect(true);
    
            // Take the PDF content
            Blob b2 = pdf2.getContentAsPDF();
    
            // Create the email attachment
            Messaging.EmailFileAttachment efa1 = new Messaging.EmailFileAttachment();
            efa1.setFileName(opp.account.Name+'-CCL.pdf');//set the email attachment name
            efa1.setBody(b1);
            
            Messaging.EmailFileAttachment efa2 = new Messaging.EmailFileAttachment();
            efa2.setFileName(opp.account.Name+'-Invoice.pdf');//set the email attachment name
            efa2.setBody(b2);
            
            // Sets the paramaters of the email
            email.setSubject(subject);//Auto populate the Subject from Template
            email.setHtmlBody(htmlBody);//Auto populate the Body from Template
            //email.setTemplateId('00Xj0000000Yg9k');//getTemplateId(opp.Product__r.Name)
            email.setTargetObjectId(opp.Account.PersonContactId);
            email.setSaveAsActivity(true);
            email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa1,efa2});
            StoringAttachments();
        }
        
        //Send email if Branch not equals to Saudi Arabia and Product type is Canada
        if(opp.Branch_Name__r.Name != 'Saudi Arabia' && opp.Product__r.Product_Type__c == 'Canada'){
            // Reference the attachment page and pass in the Opportunity ID
            PageReference pdf3 =  Page.CANCCLPdf;//CANCCLPdf is a Visualforce page
            pdf3.getParameters().put('id',opp.id); 
            pdf3.setRedirect(true);
    
            // Take the PDF content
            Blob b3 = pdf3.getContentAsPDF();
            
            PageReference pdf4 =  Page.ProformaInvoicePdf;//ProformaInvoicePdf is a Visualforce page
            pdf4.getParameters().put('id',opp.id); 
            pdf4.setRedirect(true);
    
            // Take the PDF content
            Blob b4 = pdf4.getContentAsPDF();
    
            // Create the email attachment
            Messaging.EmailFileAttachment efa3 = new Messaging.EmailFileAttachment();
            efa3.setFileName(opp.account.Name+'-CANCCL.pdf');//set the email attachment name
            efa3.setBody(b3);
            
            Messaging.EmailFileAttachment efa4 = new Messaging.EmailFileAttachment();
            efa4.setFileName(opp.account.Name+'-CANInvoice.pdf');//set the email attachment name
            efa4.setBody(b4);
            
            // Sets the paramaters of the email
            email.setSubject(subject);//Auto populate the Subject from Template
            email.setHtmlBody(htmlBody);//Auto populate the Body from Template
            //email.setTemplateId('00Xj0000000Yg9k');//getTemplateId(opp.Product__r.Name)
            email.setTargetObjectId(opp.Account.PersonContactId);
            email.setSaveAsActivity(true);
            email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa3,efa4});
            StoringAttachments();
        }
        
        //Send email if Branch is saudi Arabia and Product type is Standard
        if(opp.Branch_Name__r.Name == 'Saudi Arabia' && opp.Product__r.Product_Type__c == 'Standard'){
            // Reference the attachment page and pass in the Opportunity ID
            PageReference pdf5 =  Page.KSACCLPdf;//KSACCLPdf is a Visualforce page
            pdf5.getParameters().put('id',opp.id); 
            pdf5.setRedirect(true);
    
            // Take the PDF content
            Blob b5 = pdf5.getContentAsPDF();
            
            PageReference pdf6 =  Page.ProformaInvoicePdf;//ProformaInvoicePdf is a Visualforce page
            pdf6.getParameters().put('id',opp.id); 
            pdf6.setRedirect(true);
    
            // Take the PDF content
            Blob b6 = pdf6.getContentAsPDF();
    
            // Create the email attachment
            Messaging.EmailFileAttachment efa5 = new Messaging.EmailFileAttachment();
            efa5.setFileName(opp.account.Name+'-KSACCL.pdf');//set the email attachment name
            efa5.setBody(b5);
            
            Messaging.EmailFileAttachment efa6 = new Messaging.EmailFileAttachment();
            efa6.setFileName(opp.account.Name+'-KSAInvoice.pdf');//set the email attachment name
            efa6.setBody(b6);
            
            // Sets the paramaters of the email
            email.setSubject(subject);//Auto populate the Subject from Template
            email.setHtmlBody(htmlBody);//Auto populate the Body from Template
            //email.setTemplateId('00Xj0000000Yg9k');//getTemplateId(opp.Product__r.Name)
            email.setTargetObjectId(opp.Account.PersonContactId);
            email.setSaveAsActivity(true);
            email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa5,efa6});
            StoringAttachments();
         } 
         
         //Send email if Branch is saudi Arabia and Product type is Canada
         if(opp.Branch_Name__r.Name == 'Saudi Arabia' && opp.Product__r.Product_Type__c == 'Canada'){
            // Reference the attachment page and pass in the Opportunity ID
            PageReference pdf7 =  Page.KSACANCCLPdf;//KSACANCCLPdf is a Visualforce page
            pdf7.getParameters().put('id',opp.id); 
            pdf7.setRedirect(true);
    
            // Take the PDF content
            Blob b7 = pdf7.getContentAsPDF();
            
            PageReference pdf8 =  Page.ProformaInvoicePdf;//ProformaInvoicePdf is a Visualforce page
            pdf8.getParameters().put('id',opp.id); 
            pdf8.setRedirect(true);
    
            // Take the PDF content
            Blob b8 = pdf8.getContentAsPDF();
    
            // Create the email attachment
            Messaging.EmailFileAttachment efa7 = new Messaging.EmailFileAttachment();
            efa7.setFileName(opp.account.Name+'-KSACANCCL.pdf');//set the email attachment name
            efa7.setBody(b7);
            
            Messaging.EmailFileAttachment efa8 = new Messaging.EmailFileAttachment();
            efa8.setFileName(opp.account.Name+'-KSACANInvoice.pdf');//set the email attachment name
            efa8.setBody(b8);
            
            // Sets the paramaters of the email
            email.setSubject(subject);//Auto populate the Subject from Template
            email.setHtmlBody(htmlBody);//Auto populate the Body from Template
            //email.setTemplateId('00Xj0000000Yg9k');//getTemplateId(opp.Product__r.Name)
            email.setTargetObjectId(opp.Account.PersonContactId);
            email.setSaveAsActivity(true);
            email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa7,efa8});
            StoringAttachments();
         } 
    
            // Sends the email
            Messaging.SendEmailResult [] r = 
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email}); 
        
        
        return new PageReference('/'+opp.Id);
    }
    
    //Creating attachments
    public void StoringAttachments() {
        //Send attachments if Branch is India and Product type is Standard
        if((opp.Branch_Name__r.Name == 'India' || opp.Branch_Name__r.Name == 'United Kingdom') && opp.Product__r.Product_Type__c == 'Standard'){
            Attachment myAttach1 = new Attachment();
            myAttach1.ParentId = opp.Account.PersonContactId;
            myAttach1.name = opp.account.Name+'-CCL.pdf';
            PageReference myPdf1 = Page.CCLPdf;
            myAttach1.body = myPdf1.getContentAsPdf();
            insert myAttach1;
            
            Attachment myAttach2 = new Attachment();
            myAttach2.ParentId = opp.Account.PersonContactId;
            myAttach2.name = opp.account.Name+'-Invoice.pdf';
            PageReference myPdf2 = Page.ProformaInvoicePdf;
            myAttach2.body = myPdf2.getContentAsPdf();
            insert myAttach2;
        }
        
        //Send attachments if Branch is India and Product type is Canada
        if((opp.Branch_Name__r.Name == 'India' || opp.Branch_Name__r.Name == 'United Kingdom') && opp.Product__r.Product_Type__c == 'Canada'){
            Attachment myAttach3 = new Attachment();
            myAttach3.ParentId = opp.Account.PersonContactId;
            myAttach3.name = opp.account.Name+'-CANCCL.pdf';
            PageReference myPdf3 = Page.CANCCLPdf;
            myAttach3.body = myPdf3.getContentAsPdf();
            insert myAttach3;
            
            Attachment myAttach4 = new Attachment();
            myAttach4.ParentId = opp.Account.PersonContactId;
            myAttach4.name = opp.account.Name+'-CANInvoice.pdf';
            PageReference myPdf4 = Page.ProformaInvoicePdf;
            myAttach4.body = myPdf4.getContentAsPdf();
            insert myAttach4;
        }
        
        //Send attachments if Branch is saudi Arabia and Product type is Standard
        if(opp.Branch_Name__r.Name == 'Saudi Arabia' && opp.Product__r.Product_Type__c == 'Standard'){
            Attachment myAttach5 = new Attachment();
            myAttach5.ParentId = opp.Account.PersonContactId;
            myAttach5.name = opp.account.Name+'-KSACCL.pdf';
            PageReference myPdf5 = Page.KSACCLPdf;
            myAttach5.body = myPdf5.getContentAsPdf();
            insert myAttach5;
            
            Attachment myAttach6 = new Attachment();
            myAttach6.ParentId = opp.Account.PersonContactId;
            myAttach6.name = opp.account.Name+'-KSAInvoice.pdf';
            PageReference myPdf6 = Page.ProformaInvoicePdf;
            myAttach6.body = myPdf6.getContentAsPdf();
            insert myAttach6;
        }
        
        //Send attachments if Branch is saudi Arabia and Product type is Canada
        if(opp.Branch_Name__r.Name == 'Saudi Arabia' && opp.Product__r.Product_Type__c == 'Canada'){
            Attachment myAttach7 = new Attachment();
            myAttach7.ParentId = opp.Account.PersonContactId;
            myAttach7.name = opp.account.Name+'-KSACANCCL.pdf';
            PageReference myPdf7 = Page.KSACANCCLPdf;
            myAttach7.body = myPdf7.getContentAsPdf();
            insert myAttach7;
            
            Attachment myAttach8 = new Attachment();
            myAttach8.ParentId = opp.Account.PersonContactId;
            myAttach8.name = opp.account.Name+'-KSACANInvoice.pdf';
            PageReference myPdf8 = Page.ProformaInvoicePdf;
            myAttach8.body = myPdf8.getContentAsPdf();
            insert myAttach8;
        }
    } 
    
    //Reads the Template from Custom settings        
    public String getTemplateId(String prodName, String prodType){
       template = [Select Name, Email_Template_Id__c, Product_Type__c from Product_EmailTemplates__c 
                        where Name = : prodName and Product_Type__c = : prodType];
       return template.Email_Template_Id__c;
   }

}

Can anyone please help me to write a Test class for my Extensions?

Thanks In Advance.......
Ranjith
 
pconpcon
Since writing a test class to cover all of the facets of this class is not something that anyone on here will do for you, I can give you some pointers and hopefully get you started.  I would recommend that you do some reading on testing [1] [2] [3] to get a better understanding.  Each of your individual tests should only tests one specific portion of you class (ie a constructor test, sendEmail test, contactSelected test, etc).  You should also have both a postitive (everything works perfectly) and a negative (things are not right) test.

In your instance you will need to make part of your setup data an instance variable of you SendEmail class, and you will need to pass in a standard controller for the opportunity. [4]  I would also highly recommend that you create some utility methods to create your attachments since you have a lot of duplicate code.  This will make your testing easier to in the log run.

Each test should follow the following structure:
  • Setup of test data. This includes creation of any data needed by your class.  Account, Contacts etc
  • Starting the test. This is calling Test.startTest() to reset the governor limits
  • Calling your class / method
  • Stopping the test.This is calling Test.stopTest() to reset the governor limits and allow for any async jobs to finish
  • Asserting that your changes have worked
    • If you have inserted/updated/deleted data, you need to query for the updates
    • Run System.assert, System.assertEquals, System.assertNotEquals to verify that you got the correct data back
If you have any specific problems with your tests, feel free to create a new post with the part of the class you are trying to test and your current test method, and you will more likely get a better response then asking for someone to essentially write an entire test class for you.

[1] http://www.sfdc99.com/2013/05/14/how-to-write-a-test-class/
[2] http://http://pcon.github.io/presentations/testing/
[3] http://blog.deadlypenguin.com/blog/2014/07/23/intro-to-apex-auto-converting-leads-in-a-trigger/
[4] http://www.salesforce.com/docs/developer/pages/Content/pages_controller_error_handling.htm
Abhi_TripathiAbhi_Tripathi
rmranjith8881.3927046400771116E12rmranjith8881.3927046400771116E12
Hi Pcon and Abhi,

Thanks for reply,

Actually I wrote a Test class for it , but it covers only 8%,

I will paste my Code below, and give your valuable inputs to me.

Test Class:
 
@isTest(seeAllData=true)
public class CreateCaseTests{

    private static Id leadId;
    
static testMethod void testCreateCase() {
    
        
        //Inserting Product
        Product2 prod = new Product2();
        prod.Name = 'Marriage';
        prod.ProductCode = 'RV';
        prod.Product_Type__c = 'Standard';
        insert prod;
        
        //Inserting Products
        Product2 prod1 = new Product2();
        prod1.Name = 'Permanant Visa';
        prod1.ProductCode = 'PV';
        insert prod1;
        
        //get standard pricebook
        Pricebook2  standardPb = [select Id, Name, isActive from Pricebook2 where IsStandard = true limit 1];
        
        //Inserting pricebook
        Pricebook2 pb = new Pricebook2();
        pb.Name = 'India';
        pb.IsActive= true;
        insert pb;
        
        //Inserting pricebook
        Pricebook2 pb1 = new Pricebook2();
        pb1.Name = 'Saudi Arabia';
        pb1.IsActive= true;
        insert pb1;
        
        //Inserting pricebookEntry
        PricebookEntry pbe = new PricebookEntry();
        pbe.Pricebook2Id = standardPb.Id;
        pbe.Product2Id = prod.Id;
        pbe.UnitPrice = 1.0;
        //pbe.UseStandardPrice = true;
        pbe.IsActive = true;
        insert pbe;
        
        //Inserting pricebookEntry
        PricebookEntry pbe1 = new PricebookEntry();
        pbe1.Pricebook2Id = standardPb.Id;
        pbe1.Product2Id = prod1.Id;
        pbe1.UnitPrice = 1.0;
        //pbe.UseStandardPrice = true;
        pbe1.IsActive = true;
        insert pbe1;
        
        //Inserting Branch
        Branch__c br = new Branch__c();
        br.Name = 'India';
        br.Address_1__c = 'Marthahalli';
        br.Address_2__c = 'Near Indian oil pertol bunk';
        br.City__c = 'Bangalore';
        br.Country__c = 'India';
        br.Email__c = 'rmranjith888@gmail.com';
        br.Main_Phone_1__c = '+919590854842';
        br.Main_Phone_2__c = '+919590854842';
        br.Main_Phone_3__c = '+919590854842';
        br.Region__c = 'Bangalore';
        br.Zip_Postal_Code__c = '506007';
        insert br;
        
        Branch_Association__c ba = new Branch_Association__c();
        ba.Name = 'India';
        ba.Branch__c = br.Id;
        ba.Country__c = 'India';
        ba.Region__c = 'Bangalore';
        
        //Inserting Lead
        Lead testLead = new Lead();
            testLead.FirstName = 'Test First';
            testLead.LastName = 'Test Last';
            testLead.Status = 'Converted';
            testLead.LeadSource = 'Web';
            testLead.Date_Received__c = System.Today();
            testLead.Email = 'ranjith@rixyncs.co.in';
            testLead.Payment_Plan__c = '2 Monthly Payments';
            testLead.Phone = '+919590854842';
            testLead.MobilePhone = '+919590854842';
            testLead.CurrencyIsoCode = 'INR';
            testLead.Destination_Visa__c = 'Denmark';
            testLead.Product__c = prod.Id;
            testLead.Date_of_Birth__c = System.Today();
            testLead.Age__c = 30;
            testLead.Occupation__c = 'SE';
            testLead.Number_of_years_in_this_occupation__c = 2;
            testLead.Highest_Qualification__c = 'MCA';
            testLead.Experience__c = 'Full - Time';
            testLead.Dependents__c = '2';
            testLead.Nationality_Immigration_Status__c = 'Pending';
            testLead.Criminal_Health__c = 'No';
            testLead.Job_Offer__c = True;
            testLead.Maintenance__c = 'Yes';
            testLead.Family_Links__c = True;
            testLead.Country = 'India';
            testLead.Country__c = 'India';
            insert testLead;
            leadId = testLead.Id;
        
        
        
        Database.LeadConvert lc = new database.LeadConvert();
        lc.setLeadId(leadId);
        LeadStatus convertStatus = [Select Id, MasterLabel from LeadStatus where IsConverted=true limit 1];
        lc.setConvertedStatus(convertStatus.MasterLabel);
        
        Database.LeadConvertResult lcr = Database.convertLead(lc);
    System.assert(lcr.isSuccess());

RecordType myRecordType = [select id from RecordType where SobjectType='Account' AND IsPersonType=True limit 1];
    
        //Inserting Account
        Account acc = new Account();
        acc.LastName = 'Ranjith';
        acc.RecordTypeId = myRecordType.Id;
        insert acc;
        
        //Inserting Contact
        Contact con = new Contact();
        con.LastName = 'kumar';
        insert con;    
              
                
        
        
        //Inserting Potential
        Opportunity opp = new Opportunity();
        opp.Name = 'Ranjith-';
        opp.AccountId = acc.Id;
        opp.CloseDate = System.today()+20;
        opp.StageName = 'CCL Sent';
        opp.Contact_Name__c = con.Id;
        opp.Type  = 'Existing Business';
        opp.English_Language__c  = 'Vocational';
        opp.Payment_Plan__c = '3 Monthly Payments';
        opp.Tax_Amount__c = 0.00;
        opp.Total_after_Tax__c = 1000000.00;
        opp.Amount = 9500.00;
        opp.Date_of_Birth__c = System.today();
        opp.Destination_Visa__c = 'US';
        opp.TimeFrame__c = '3 Months';
        opp.Eligibility_Score__c = 60;
        opp.Branch_Name__c = br.Id;
        opp.Occupation__c = 'SE';
        opp.Number_of_years_in_this_occupation__c = 2;
        opp.Highest_Qualification__c = 'MCA';
        opp.Experience__c = 'Full - Time';
        opp.Dependents__c = '2';
        opp.Nationality_Immigration_Status__c = 'Pending';
        opp.Criminal_Health__c = 'No';
        opp.Job_Offer__c = True;
        opp.Maintenance__c = 'Yes';
        opp.Family_Links__c = True;
        opp.payment_1_Amount__c = 100.00;
        opp.Payment_2_Amount__c = 100.00;
        opp.Payment_3_Amount__c = 100.00;
        opp.Payment_1_Received_Date__c = System.today();
        opp.Payment_2_Due_Date__c = System.today()+30;
        opp.Payment_3_Due_Date__c = System.today()+60;
        opp.Payment_1_Before_Tax__c = 100.00;
        opp.Payment_2_Before_Tax__c = 100.00;
        opp.Payment_3_Before_Tax__c = 100.00;
        opp.Payment_1_Status__c = 'Received';
        opp.Payment_2_Status__c = 'Pending';
        opp.Payment_3_Status__c = 'Pending';   
        opp.Pricebook2Id  = pbe.Pricebook2Id; 
        opp.Product__c = prod.Id;
        opp.Email__c = 'ranjith@rixyncs.co.in';
        opp.Payment_1_Tax_Amount__c = 100.00;
        insert opp;

ApexPages.StandardController stdController = new ApexPages.StandardController(opp); 
        SendEmail send = new SendEmail(stdController);
        
       // Product_EmailTemplates__c is Custom settings to read the template Id and Product Type
        Product_EmailTemplates__c template = new Product_EmailTemplates__c();
        template.Name = 'Tourist';
        template.Email_Template_Id__c = '00X11000000QtEi';
        template.Product_Type__c = 'Stnadard';
        insert template;
        
        System.currentPagereference().getParameters().put('id',opp.id);

Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
         
         PageReference pdf1 =  Page.CCLPdf;//CCLPdf is a Visualforce page
            pdf1.getParameters().put('id',opp.id); 
            pdf1.setRedirect(true);
            
            // Take the PDF content
            Blob b1;
            
         if (Test.IsRunningTest()){
                b1 = Blob.valueOf('UNIT.TEST');
             }else{
                b1 = pdf1.getContent();
             }
    
            
            
            PageReference pdf2 =  Page.ProformaInvoicePdf;//ProformaInvoicePdf is a Visualforce page
            pdf2.getParameters().put('id',opp.id); 
            pdf2.setRedirect(true);
            
            // Take the PDF content
            Blob b2;
            
            if (Test.IsRunningTest()){
                b2 = Blob.valueOf('UNIT.TEST');
             }else{
                b2 = pdf2.getContent();
             }
    
            
         
         Messaging.EmailFileAttachment efa1 = new Messaging.EmailFileAttachment();
            efa1.setFileName(opp.account.Name+'-CCL.pdf');//set the email attachment name
            efa1.setBody(b1);
            
         Messaging.EmailFileAttachment efa2 = new Messaging.EmailFileAttachment();
            efa2.setFileName(opp.account.Name+'-Invoice.pdf');//set the email attachment name
            efa2.setBody(b2);
            
             // Sets the paramaters of the email
            email.setSubject('subject');//Auto populate the Subject from Template
            email.setHtmlBody('htmlBody');//Auto populate the Body from Template
            //email.setTemplateId('00Xj0000000Yg9k');//getTemplateId(opp.Product__r.Name)
            email.setTargetObjectId(opp.Account.PersonContactId);
            email.setSaveAsActivity(true);
            email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa1,efa2});
            
             // Sends the email
            Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email}); 
       
        
        send.send();
        send.StoringAttachments();
        send.getTemplateId('Permanant Visa','Standard');
        
        
   }
}
I am getting the error in this line:

Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});

This is my Error:
System.EmailException: SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Missing target address (target, to, cc, bcc): []

Here, to,cc,bcc are optional, if I am not taking those also it should work

Can you please look into it and let me know what's wrong in my code?

Thanks in advance....
Ranjith
 
Tejpal KumawatTejpal Kumawat
Hello Friend,

setTargetObjectId must be ID of the contact, lead, or user to which the email will be sent.
Check in your code is that ID coming correctly or not & also check is email ID mentioned or not in test data.

If this answers your question then hit Like and mark it as solution!