0

I have done custom email component, but when I try to attach a file I receive this exception -

SendEmail failed. First exception on row 0; first error: INVALID_ID_FIELD, The ID provided is not of types ContentVersion or Document.: [entityAttachments, 06A6E000000f3RMUAY] Please contact your administrator for details.

What is my mistake?

Apex Controller

/**
 * Created by Evgeniya.Zaneva on 4.2.2019 
 *  A class used to send email messages to lead
 */

public class EmailServiceOutbound {

    @AuraEnabled 

    public static void sendMailMethod(String mMail ,String mSubject ,String mbody,String recordId,List<String> attach){

       System.debug('>>email>>>'+mMail);
       System.debug('>>subject>>>'+mSubject);
       System.debug('>>body>>>'+mbody);

       LPG_PP_Email_Component_Data__c addressData = LPG_PP_Email_Component_Data__c.getInstance();

        //Inserting the record id in Email subject

        String subjectRecord= ' ('+ recordId +')';

        //Email Sending Start
        List<Messaging.SingleEmailMessage> mails =  new List<Messaging.SingleEmailMessage>();
        //Create a new Email
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();        

        //Set list of people who should get the email        

        List<String> sendTo = mMail.split(',');
        System.debug('send to'+sendTo);

        //Setting Senders
        mail.setToAddresses(sendTo);
        String addrUrl = addressData.LPG_Email_Service_Address__c;
        // Set who the email is sent from


        Id userId = UserInfo.getUserId();
        List<User>us = [SELECT Id, Username, AccountId FROM User where Id=:userId LIMIT 1];
        if (us.size()>0) {
        System.debug('user'+us);
        }

        List<Account> acc = [SELECT Id,Name,LPG_Primary_Contact__c,LPG_ExternalEmail_Portal__c FROM Account where Id =: us[0].AccountId LIMIT 1];

        String accEmail;
        String accName;
        mail.setReplyTo(addrUrl); // change it with your mail address.
      //  mail.setSenderDisplayName(accName);

        // Subject from Email Component and Record ID

      OrgWideEmailAddress[] owea = [SELECT Id,DisplayName,Address FROM OrgWideEmailAddress WHERE Address = :addressData.LPG_Org_Wide_Email_Address__c];
        if ( owea.size() > 0 ) {
            System.debug('Id'+owea.get(0).Id);
            mail.setOrgWideEmailAddressId(owea.get(0).Id);
            accName = owea.get(0).DisplayName;
            accEmail = owea.get(0).Address;
        }

        if (!mSubject.contains(subjectRecord)) {
            mail.setSubject(mSubject + subjectRecord );
        }
        else{
            mail.setSubject(mSubject);
        }

        //Setting Body from Email Component
        if (mbody==null) {
            mbody = '';
        }
        mail.setHtmlBody(mbody);
        system.debug('attach'+attach);
        try{
            List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
            for (ContentDocumentLink a : [SELECT id,ContentDocument.Title,ContentDocument.FileType,ContentDocument.FileExtension,
                    ContentDocument.LatestPublishedVersionId,ContentDocument.LatestPublishedVersion.VersionData
            FROM ContentDocumentLink WHERE LinkedEntityID =:recordId])
            {
                Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
                efa.setFileName(a.ContentDocument.Title+'.'+a.ContentDocument.FileExtension);
                //a.ContentDocument.LatestPublishedVersion.VersionData is a Base64 String. Converting it into Blob
                String blobValue = EncodingUtil.base64Encode(a.ContentDocument.LatestPublishedVersion.VersionData);
                efa.setBody(EncodingUtil.base64Decode(blobValue));
                system.debug(a);
                fileAttachments.add(efa);
            }
            system.debug(fileAttachments);
            mail.setEntityAttachments(attach);
        }
        catch (Exception e){
            system.debug('attach issue'+e.getMessage());
        }

        // Add your email to the master list
        mails.add(mail);


            //Add Inbound Email Message for contact
            EmailMessage leadEmailMessage = new EmailMessage();

            leadEmailMessage.FromAddress= accEmail;
            leadEmailMessage.ToAddress = mMail;
            leadEmailMessage.FromName = accName;
            leadEmailMessage.Subject = mSubject;
            leadEmailMessage.HtmlBody = mbody;
            leadEmailMessage.Incoming= False;
            leadEmailMessage.TextBody = mbody ;
            leadEmailMessage.Status = '3';

        List<Lead> lead = [SELECT Id FROM Lead WHERE Id=:recordId];
        if (lead.size()>0) {
            leadEmailMessage.Lead__c = recordId;
            System.debug('leAd'+leadEmailMessage.Lead__c);
            try {
                // Send all emails in the master list
                Messaging.sendEmail(mails);
                System.debug('>>>>>==Emails' + mails);
                insert leadEmailMessage;
                System.debug('>>>>>==' + leadEmailMessage);
                System.debug('>>>>>==' + leadEmailMessage.Id);
                // Add Email Message Relation for id of the sender
                EmailMessageRelation emr = new EmailMessageRelation();
                emr.EmailMessageId = leadEmailMessage.Id;
                emr.RelationAddress = accEmail;
                emr.RelationType = 'FromAddress';
                //Lead Email Message Relation Id
                emr.RelationId = recordId;
                insert emr;
                System.debug('>>>>>==Email Relation' + emr);

            }
            catch(Exception e){
               //todo:uncomment lines
                System.debug('Query Issue: ' + e.getMessage());
                Messaging.SingleEmailMessage replyMail = new Messaging.SingleEmailMessage();
                List<String> toAddresses = new List<String>();
                toAddresses.add('[email protected]');
                //toAddresses.add('[email protected]');
                replyMail.setToAddresses(toAddresses);
                //replyMail.setReplyTo('[email protected]');
                replyMail.setSenderDisplayName('Info Lampuga');
                replyMail.setSubject('Query Exception');
                String additionalExcMessage = ' Please contact your administrator for details';
                replyMail.setHtmlBody(e.getMessage()+additionalExcMessage);

                Messaging.sendEmail(new Messaging.SingleEmailmessage[] {replyMail});

            }
        }

    }
}

JS Controller

({
    sendMail: function(component, event, helper) {
        var getEmail = component.get("v.email");
        var getSubject = component.get("v.subject");
        var getbody = component.get("v.bodytext");
        var getrecid = component.get("v.recordId");
        var attachments = component.get("v.files");
        // check if Email field is Empty or not contains @ so display a alert message
        // otherwise call call and pass the fields value to helper method
        if ($A.util.isEmpty(getEmail) || !getEmail.includes("@")) {
            alert('Please Enter valid Email Address');
        }
        else if($A.util.isEmpty(getSubject)){
              alert('Please Enter Subject');
        }
        else {
            helper.sendHelper(component, event, helper,getEmail, getSubject, getbody,getrecid,attachments);
        }
    },

    // when user clicks on the close buttton on message popup
    closeMessage: function(component, event, helper) {
        component.set("v.mailStatus", false);
        component.set("v.email", null);
        component.set("v.subject", null);
        component.set("v.bodytext", null);
        component.set("v.files", null);
    },
      uploadFile: function(component, event, helper){
             var uploadedFiles = component.get("v.files");
             var singleFile = event.getParam("files");
             console.log('singlefile',singleFile);
             //console.log('document Id2-->'+singleFile.get('documentId'));
             for(var i = 0; i < singleFile.length; i++){
               //  console.log('elements--'+JSON.stringify(singleFile[i].documentId));
                 uploadedFiles.push(singleFile[i].documentId);
             }
             component.set("v.files", uploadedFiles);
            console.log(component.get("v.files"));
         }
})

Helper

({
    sendHelper: function(component,event,helper, getEmail, getSubject, getbody,getrecid,attachments) {
        var action = component.get("c.sendMailMethod");
        action.setParams({
            'mMail': getEmail,
            'mSubject': getSubject,
            'mbody': getbody,
            'recordId':getrecid,
            'attach':attachments
        });

        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var storeResponse = response.getReturnValue();
                var applicationEvent = $A.get("e.c:EventCloseModelPopup");
                applicationEvent.setParams({"message" : 'success'})
                applicationEvent.fire();
            }
        });
        $A.enqueueAction(action);
    }

})

Component

<aura:component controller="EmailServiceOutbound"
                implements="force:hasRecordId,force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,lightning:actionOverride,forceCommunity:availableForAllPageTypes,force:lightningQuickActionwithoutHeader">
   <!--Part 1 [for attribute declare]-->
   <aura:attribute name="email" type="String"/>
   <aura:attribute name="subject" type="String"/>
   <aura:attribute name="bodytext" type="String"/>
   <aura:attribute name="recordId" type="Id" />
   <aura:attribute name="files" type="List"/>

   <lightning:overlayLibrary aura:id="overlayLib"/>
   <aura:registerEvent name="closeModelPopupEvent" type="c:EventCloseModelPopup"/>
   <!---Part 2 [header part] -->

   <div class="slds-page-header" role="banner" id="banner">

      <h1 class="slds-page-header__title slds-m-right--small slds-align-middle slds-truncate" title="New Email">

         New Email

      </h1>

   </div>

   <!---Part 4 [mail fourm part]-->   

   <div class="slds-m-around--medium" id="mainDiv">

      <div class="slds-container--medium">

         <div class="slds-form--stacked">

            <div class="slds-form-element">

               <label class="slds-form-element__label" for="CC">Subject</label>

               <div class="slds-form-element__control">

                  <ui:inputText class="slds-input" aura:id="subject"  value="{!v.subject}" placeholder="Subject"/>

               </div>

            </div>

            <div class="slds-form-element">

               <label class="slds-form-element__label" for="textareaSample2">Mail Body</label>

               <div class="slds-form-element__control">

                  <lightning:inputRichText aura:id="body" value="{!v.bodytext}" />

               </div>

            </div>
            <div class="slds-form-element">
               <div class="slds-form-element__control">
                  <lightning:fileUpload label="Attach File" multiple="true" accept=".pdf, .png, .txt" recordId="{!v.recordId}"  onuploadfinished="{!c.uploadFile}" />
               </div>
            </div>

            <div class="slds-form-element">    

               <button class="slds-button slds-button--brand" onclick="{!c.sendMail}">Send</button>

            </div>

         </div>

      </div>

   </div>

</aura:component>

1 Answer 1

4

06A is the key prefix for ContentDocumentLink, which points to the bug here:

        system.debug(fileAttachments);
        mail.setEntityAttachments(attach);

You are calling setEntityAttachments() with a variable, attach, whose type is not compatible with that method. attach is a List<String> whose contents are ContentDocumentLink Ids, and that method takes Document, ContentVersion, or Attachment Ids.

You seem to have been building input for a call to setFileAttachments(), which does take a List<EmailFileAttachment>.

2
  • setEntityAttachments(ids) Optional. Array of IDs of Document, ContentVersion, or Attachment items to attach to the email. So I dont need fileAttachments because its from type - Messaging.Emailfileattachment Apr 30, 2019 at 13:47
  • Well, you need to pick one or the other. I tried to clarify my answer.
    – David Reed
    Apr 30, 2019 at 13:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .