2

I'm trying create component to send an email with attachment. I'm using standard lightning:fileUpload to upload files and save to specific record. I know using this files are stored as ContentDocument, I'm not able to attach uploaded file to email because I'm getting ContentDocument Id instead of attachment Id. How to resolve this? following is the piece of code :

Component

<aura:component implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global" controller="SendEmailController">
<aura:attribute name="to" type="String"/>
<aura:attribute name="cc" type="String"/>
<aura:attribute name="bcc" type="String"/>
<aura:attribute name="subject" type="String"/>
<aura:attribute name="body" type="String"/>
<aura:attribute name="from" type="OrgWideEmailAddress[]" />
<aura:attribute name="files" type="List"/>
<aura:handler name="init" action="{!c.doInit}" value="{!this}"/>

<div class="slds-container--medium">
    <div class="slds-form">
        <div class="slds-form-element">
            <div class="slds-form-element__control">
                <lightning:select name="select" label="From:" aura:id="fromId">
                    <option value="">--None--</option>
                    <aura:iteration items="{!v.from}" var="frmAdd">
                        <option text="{!frmAdd.DisplayName}" value="{!frmAdd.Address}"></option>
                    </aura:iteration>
                </lightning:select>
            </div>
        </div>
        <div class="slds-form-element">
            <div class="slds-form-element__control">
                <lightning:input type="email" aura:id="isValid" label="To:" value="{!v.to}" name="toAddress" required="true" messageWhenRangeUnderflow="Please provide valid email"/>
            </div>
        </div>
        <div class="slds-form-element">
            <div class="slds-form-element__control">
                <lightning:input type="email" aura:id="isValid" label="CC:" value="{!v.cc}" name="cc" messageWhenRangeUnderflow="Please provide valid email"/>
            </div>
        </div>
        <div class="slds-form-element">
            <div class="slds-form-element__control">
                <lightning:input type="email" aura:id="isValid" label="BCC:" value="{!v.bcc}" name="bcc" messageWhenRangeUnderflow="Please provide valid email"/>
            </div>  
        </div>
        <div class="slds-form-element">
            <div class="slds-form-element__control">
                <lightning:input type="text" label="Subject:" name="subject" value="{!v.subject}"/>
            </div>
        </div>
        <div class="slds-form-element">
            <div class="slds-form-element__control">
                <label class="slds-form-element__label" >Body:</label>
                <lightning:inputRichText placeholder="Type email body" value="{!v.body}"/>
            </div>
        </div>
        <div class="slds-form-element">
            <div class="slds-form-element__control">    
                 <lightning:fileUpload label="Upload File" multiple="true" accept=".pdf, .png, .txt" recordId="{!v.recordId}" aura:id="multifileUpload" onuploadfinished="{!c.uploadFile}" />
            </div>
        </div>
        <div class="slds-form-element">
            <div class="slds-form-element__control">    
                <lightning:button class="slds-button slds-button--brand" onclick="{!c.sendEmail}">Send</lightning:button>
            </div>
        </div>
    </div>
</div>

Apex Controller

public with sharing class SendEmailController {


    @AuraEnabled
    public static void sendEmailAction(String eTo, String eCc, String eBcc, String eSubject, String eBody, String eFrom, List<String> attach){
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();

        System.debug('attach--'+attach);
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

        mail.setToAddresses(new List<String>{eTo});

        if(eCc != '' && eCc != null)
            mail.setCcAddresses(new List<String>{eCc});

        if(eBcc != '' && eBcc != null)
            mail.setBccAddresses(new List<String>{eBcc});

        mail.setSubject(eSubject);
        if(eFrom != null)
            mail.setInReplyTo(eFrom);

        List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
        /*for (ContentDocument a : [select Id, Title from ContentDocument where Id = :attach])
        {
            Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
            efa.setFileName(a.Title);
            efa.setBody(a.Body);
            fileAttachments.add(efa);
        }*/
        mail.setEntityAttachments(attach);
        mail.setHtmlBody(eBody);
        mails.add(mail);
        System.debug('Email-->>'+mails);
        /*Messaging.SendEmailResult[] results = Messaging.sendEmail(mails);

        if (results[0].success)
            System.debug('The email was sent successfully.');
        else
            System.debug('The email failed to send: ' + results[0].errors[0].message);*/
    }

    @AuraEnabled
    public static List<OrgWideEmailAddress> getOrgWideEmailAddress(){
        return [SELECT Id, Address, DisplayName from OrgWideEmailAddress];
    }
}

JS Controller

({

    doInit: function(component, event, helper) {
        var action = component.get("c.getOrgWideEmailAddress");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.from", response.getReturnValue());
            }
            else {
                console.log("Failed with state: " + state);
            }
        });
        $A.enqueueAction(action);
    },
    sendEmail: function(component, event, helper) {
        var to = component.get("v.to");
        var cc = component.get("v.cc");
        var bcc = component.get("v.bcc");
        var subject = component.get("v.subject");
        var body = component.get("v.body");
        var from = component.find("fromId").get("v.value");
        //console.log('files before send--'+JSON.stringify(component.get("v.files")));
        var attachments = component.get("v.files");
        //console.log('Added attachments--'+attachments.length);
        var validEmail = component.find('isValid').reduce(function (validSoFar, inputCmp) {
                inputCmp.showHelpMessageIfInvalid();
            return validSoFar && inputCmp.get('v.validity').valid;
        }, true);
        if(validEmail){
            console.log('attachments---'+JSON.stringify(attachments));
            helper.sendEmailHelper(component, to, cc, bcc, subject, body, from, attachments);
        }
    },
    uploadFile: function(component, event, helper){
        var uploadedFiles = component.get("v.files");
        var singleFile = event.getParam("files");
        //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(JSON.stringify(singleFile[i].documentId));
        }
        component.set("v.files", uploadedFiles);
    }
})

**JS Helper**

    ({
    sendEmailHelper : function(component, getTo, getCc, getBcc, getSubject, getBody, getFrom,getAttachments) {
        var action = component.get("c.sendEmailAction");
        console.log('getAttachments in helper--'+JSON.stringify(getAttachments));
        action.setParams({
            'eTo' : getTo,
            'eCc' : getCc,
            'eBcc': getBcc,
            'eSubject' : getSubject,
            'eBody' : getBody,
            'eFrom' : getFrom,
            'attach' : getAttachments
        });

        action.setCallback(this, function(response) {
            var state = response.getState();
            if(state == "SUCCESS")
                alert('Email Send successfully..!!');
            else
                alert('Failed to send Email..!!');
        });

        $A.enqueueAction(action);
    }
})
4

As you are using lightning:fileUpload it will create a contentDocument and ContentDocumentLink. It does not make sense to query Attachments.

Thus your SOQL will be on ContentDocumentLink and would fetch body needed for email attachment.

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 =:attach])
{
    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
    efa.setBody(EncodingUtil.base64Decode(a.ContentDocument.LatestPublishedVersion.VersionData));

    fileAttachments.add(efa);
}
  • Thanks @Pranay.. issue was with soql. It's working now. Have to query on ContentDocument instead Attachments – Atul Rakate May 22 '18 at 13:00
  • You can make answer as solved, that will close this thread. – Pranay Jaiswal May 22 '18 at 13:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.