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
Sfdc wonderSfdc wonder 

How to send Multiple attachments to mail

Hi,
My Lead having Notes&Attachments in related list.i want to send multiple attachment to mail at a time by selecting attachments .
any one give me idea how i acheive this...

thanks in advance
qraishqraish

Here's something you might want to try in messaging.singleemailmessage method:

List<Messaging.EmailFileAttachment> lstLeadEmailAttachments = new List<Messaging.EmailFileAttachment>;

for(Attachment leadAtt: lstLeadAttach)
{
   Messaging.EmailFileAttachment lea = new Messaging.EmailFileAttachment();
   lea.setFileName(leadAtt.Name);
   lea.setBody(leadAtt.Body);
   lea.setContentType(leadAtt.ContentType);
   lstLeadEmailAttachments.add(lea);
}
mail.setFileAttachments(lstemailAttachments);

DevADSDevADS
Hello BuzzBoard,

1) Create an Inline Visualforce Page & use Lead as standard Controller Where you will fetch all the attachments of Related Leads & will have checkbox associated with every Attachments.
2) Create a Class & a wrapper class. In Wrapper Class you will have two variable one will be Attachment Id & one will be boolean.
3) Now the User will select the checkbox, the wrapper list reference will be updated.
4) You will have one button in Visualforce page "Send Attachments" , on which you will call apex method Where you will fetch all the selected attachment Ids.
Hint.
for(wrapper_SelectedImages attItr : wrapList){
            if(attItr.isSelected == true){
                selectedAttachment.add(attItr.wrapAttachfileId);
            }
        }

5) Now you will send all the Selected attachment Ids & mail.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
       List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
       for (Attachment attachItr : [SELECT id,Name,Body FROM Attachment WHERE id IN: selectedAttachment])
        {
            Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
            efa.setFileName(attachItr.Name);
            efa.setBody(attachItr.Body);
            fileAttachments.add(efa);
        }
        mail.setFileAttachments(fileAttachments);
        System.debug('===email'+EmailAddress);
        mail.setToAddresses(EmailStrings);
        mail.setSubject(propertyName);
        mail.setHtmlBody('Dear '+ EmailName +', <br/>'+ etInst.htmlValue );
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

You can modify the code as per your requirement. If you are still facing any issue, Let me know!

Note : Don't fetch the attachment's body, Just fetch the attachment Ids. You will fetch the body only when you are adding it in Messaging.EmailAttachment list Else you may face the View State error.
Happy Coding!

Sfdc wonderSfdc wonder
Hi Amit_Shingavi,
Thanks for your reply.

im trying as mention above.but emails are not successfully sent.
can you plz tell me my mistakes&im trying to send to lead email by deafault


<apex:page standardController="Lead" extensions="Checkbox_Class">
  <apex:form >
   <apex:pageBlock title="Attachments">
   <apex:pageBlockButtons >
            <apex:commandButton value="SendEmails" action="{!getSelected}"/>
        </apex:pageBlockButtons>

     <apex:pageBlockTable value="{!Lead.Attachments}" var="Att">
     <apex:column headerValue="Select">
            <apex:inputCheckbox value="{!lead.attachments}"/>
        </apex:column>
       <apex:column value="{!Att.createddate}"/>
       <apex:column value="{!Att.name}"/>
       <apex:column value="{!Att.description}"/>
     </apex:pageBlockTable>
    
      </apex:pageBlock>
  </apex:form>
</apex:page>



public class Checkbox_Class
{

public class Attachmentwrapper
   {
      public Attachment acc{get; set;}
      public Boolean selected {get; set;}
      public Attachmentwrapper(Attachment a)
      {
          acc = a;
             
      }
    }
        public Id leadids{get;set;}        
        public Checkbox_Class(ApexPages.StandardController ctrl)   
        {      
        leadids= ctrl.getRecord().Id;        
        }
   
        List<Attachmentwrapper> AttachmentList = new List<Attachmentwrapper>();
        List<Attachment> selectedAttachments = new List<Attachment>();
      
        public List<Attachmentwrapper> getAttachments()
        {
            for(Attachment a : [select Id, Name, Body, BodyLength from Attachment where ParentId = :leadids])
              {     
                AttachmentList.add(new Attachmentwrapper(a));
           
              }
              return AttachmentList;
        }
        
        public PageReference getSelected()
        {
          
         Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
         String[] toAddresses = new String[]{'buzzboardsf@gmail.com'};
         mail.setToAddresses(toAddresses);
         mail.setReplyTo('buzzboardsf@gmail.com');
         mail.setSenderDisplayName('CRM Support');
         mail.setBccSender(false);
         mail.setUseSignature(false);
        // mail.setTargetObjectId('005Q0000000FR7f');
        // mail.setTemplateId('00XQ0000000QULj');
        // mail.saveAsActivity = false;
                         
         //selectedAttachments.clear();
         for(Attachmentwrapper accwrapper : AttachmentList)
         {
         if(accwrapper.selected == true)
         {
         List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
             for (Attachment a : [select Id, Name, Body, BodyLength from Attachment where ParentId = :leadids])
                {
                     Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
                     efa.setFileName(a.Name);
                     efa.setBody(a.Body);
                     fileAttachments.add(efa);
                }
          
                mail.setFileAttachments(fileAttachments);
         selectedAttachments.add(accwrapper.acc);
         Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        
         }
        }      
      
       return null;
      }
}


DevADSDevADS
Hey BuzzBoard,

I have customized the code, You just Copy paste it & change it as per your requirement.

VF Page:
<apex:page standardController="Lead" extensions="checkbox_Class" showChat="false" showheader="false" sidebar="false" standardStylesheets="false">
       <apex:form id="form1">
         <apex:outputPanel id="Opp1" rendered="{!render1}">
            <apex:commandButton value="Send Pictures" action="{!SendAttachment}"/><br/><br/>
          
                <table width="20%" cellspacing="1px">
                    <tr>
                        <apex:repeat value="{!wrapperList}" var="wrap">
                            <td width="20px">
                            <center><img src="https://c.ap1.content.force.com/servlet/servlet.FileDownload?file={!wrap.wrapAttachfileId}" height="100" width="100"></img><br/>
                            <apex:inputCheckbox value="{!wrap.isSelected }"/></center>
                            </td>
                         </apex:repeat>
                    </tr>
                </table>
            </apex:outputPanel>
           
            <apex:outputPanel id="Opp2" rendered="{!render2}">
                To<label style="color:RED">*</label>:&nbsp;&nbsp;&nbsp;
                <apex:inputText id="emailName" value="{!EmailName}" required="true" size="50"/>&nbsp;&nbsp;&nbsp;
                Email<label style="color:RED">*</label>:&nbsp;&nbsp;&nbsp;
                <apex:inputText id="emailInput" value="{!EmailAddress}" required="true" size="50"/><br/><br/>
               
                <apex:repeat value="{!selectedAttachment}" var="wrap1">
                    <img src="https://c.ap1.content.force.com/servlet/servlet.FileDownload?file={!wrap1}" height="100" width="100"></img>
                 </apex:repeat><br/>
                <apex:commandButton value="Send" action="{!SendEmail}"/>
            </apex:outputPanel>
    </apex:form>
   
</apex:page>

Apex Controller:
public class checkbox_Class
{
    public String propertyId{get;set;}
    public String propertyName{get;set;}
    private final Lead propertyInstance {get;set;}
    @TestVisible public List<wrapper_SelectedImages> wrapList {get; set;}
    public List<Id> selectedAttachment {get; set;}
    public String EmailAddress {get;set;}
    public String EmailName {get;set;}
    public Boolean Render1 {get; set;}
    public Boolean Render2 {get; set;}
       
    public checkbox_Class(ApexPages.standardController controller)
    {
          Render1 = true;
          propertyId = (String)controller.getRecord().id;
          propertyInstance = [SELECT id,Name FROM Lead WHERE Id=:propertyId LIMIT 1];
          propertyName = propertyInstance.Name;
    }
   
    public List<wrapper_SelectedImages> getwrapperList(){
        System.debug('=='+propertyId);
        if(wrapList == null){
            wrapList = new List<wrapper_SelectedImages>();
           
            for(Attachment attachItr : [SELECT id,parentId from Attachment WHERE ParentId=: propertyId ]){
                wrapList.add(new wrapper_SelectedImages(attachItr.id));
            }
      }
       return wrapList;
    }
   
    public pageReference SendAttachment(){
        selectedAttachment = new List<Id>();
        System.debug('==='+wrapList);
        for(wrapper_SelectedImages attItr : wrapList){
            if(attItr.isSelected == true){
                selectedAttachment.add(attItr.wrapAttachfileId);
            }
        }
        Render1 = false;
        Render2 = true;
        return null;
     }
  
    public void SendEmail(){
    List<String> EmailStrings = new List<String>();
    EmailStrings = EmailAddress.split(',');
    //EmailTemplate etInst = [SELECT htmlValue FROM EmailTemplate WHERE developername='Picture_Gallary_Custom' LIMIT 1];
   
    try{
       Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
       List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
       for (Attachment attachItr : [SELECT id,Name,Body FROM Attachment WHERE id IN: selectedAttachment])
        {
            Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
            efa.setFileName(attachItr.Name);
            efa.setBody(attachItr.Body);
            fileAttachments.add(efa);
        }
        mail.setFileAttachments(fileAttachments);
        System.debug('===email'+EmailAddress);
        mail.setToAddresses(EmailStrings);
        mail.setSubject(propertyName);
        mail.setHtmlBody('Dear '+ EmailName +', <br/>');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }catch(Exception e){
        System.debug('====exception'+e);
    }
   
        Render1 = true;
        Render2 = false;
        for(wrapper_SelectedImages wraper : wrapList)
        {
        wraper.isSelected = false;
        }
        EmailAddress = '';
        EmailName = '';
        }
    
    @TestVisible public Class wrapper_SelectedImages{
        public Boolean isSelected {get;set;}
        public Id wrapAttachfileId {get;set;}
       
        public wrapper_SelectedImages(Id attachfileId){
            this.isSelected = false;
            this.wrapAttachfileId = attachfileId;
        }
    }
}

Happy Coding!!
DevADSDevADS
Hey BuzzBoard,

Let me know if you still face any issue!
DevADSDevADS
Note : Your Instance URL may be different, You need to change it in <img> tag.
Sfdc wonderSfdc wonder
Hi Amith,
im facing the following error 
"  Illegal assignment from LIST<Lead> to Lead at line 17 column 11    "
at 
propertyInstance = [SELECT id,Name FROM Lead WHERE Id=:propertyId LIMIT 1];
DevADSDevADS
I have tried it in another org, It's working fine for me! & the query shouldn't return list as we are limiting it with 1!
Sfdc wonderSfdc wonder
Hi Amith,

im getting 'Methods defined as TestMethod do not support Web service callouts, test skipped' in my test class.
can u suggest anything....

@isTest
public class SendEmail_bb_Test
{
@isTest static void SendEmailTestMethod()
{

    
    Lead objlead=new Lead(LastName='test lead',company='vs',Street='test',city='test',postalcode='test',state='ap',country='ind',phone='9948155656');
    insert objlead;
    
     System.currentPagereference().getParameters().put('id',objlead.id);
    
     Attachment objAtt = new Attachment();
     objAtt.Name = 'Test';
     objAtt.body = Blob.valueof('string');
     objAtt.ParentId = objLead.Id;
     insert objAtt;
    
     ApexPages.StandardController sc =new ApexPages.StandardController(objlead);  
     SendEmail_bb b=new SendEmail_bb(sc);
     SendEmail_bb.wrapper_SendEmails sb=new SendEmail_bb.wrapper_SendEmails(objAtt.id,objAtt.Name);
    
     List<SendEmail_bb.wrapper_SendEmails>wrapList=new List<SendEmail_bb.wrapper_SendEmails>();
     wrapList.add(new SendEmail_bb.wrapper_SendEmails(objAtt.id,objAtt.Name));
    
    
     b.EmailAddress='ram@gmail.com';
     b.EmailName='Ram';
     sb.isSelected=true;
     sb.attachName=objAtt.Name;
     sb.wrapAttachfileId=objAtt.id;
  
     b.getwrapperList();
     b.SendAttachment();
     b.SendEmail();
   

}
}