More

    How to create a file from an email attachment in Salesforce

    Even though Salesforce has a number of restrictions and limitations – which are for valid reasons, there still are many tools and apex workarounds that can solve our problems. We recently covered how to start a process builder after one minute. Now, it’s time to help our users in creating a file from an email attachment in Salesforce.

    We know that with Salesforce’s Messaging.InboundEmailHandler class, we can retrieve the inbound email object and retrieve the email’s content, subject, attachments and then perform many different functions such as creating a lead, etc. However, dealing with attachments is slightly different from other content which is mainly retrieved in the form of text.

    The email attachments are presented in the form of URLs in the email object. These external URLs – when accessed – can get us to our required file, however, we can’t directly get the file or attachment from the email object.

    So, what can we do if we also need to get the email attachments in Salesforce in the same format they were uploaded? We can convert the URLs to files using Apex and then store them into Salesforce. Following are the points you to understand:

    • Get the attachment’s URL from email object
    • Access the url via HTTP request
    • Retrieve the content of the attachment as a blob
    • Use that blob to create a ContentVersion (File)
    • Create a Content Document Link and link it with the desired record

    You can use the code below to better understand the solution

    global blob fetchFileFromExternalUrl(String extFileUrl)
        {   
            Http h = new Http(); 
            HttpRequest req = new HttpRequest(); 
            extFileUrl = extFileUrl.replace(' ', '%20');  // Replace spaces with %20 
            req.setEndpoint(extFileUrl); 	 // Set the end point URL
            req.setMethod('GET'); 
            req.setHeader('Content-Type', 'application/pdf'); 
            req.setCompressed(true); 
            req.setTimeout(60000);
    
            Blob retFile;
            if(!Test.isRunningTest())
            {
                HttpResponse res = h.send(req);   // Now Send HTTP Request
                retFile = res.getBodyAsBlob();  // Convert the response into Blob 
            }
            else
            {
                retFile = Blob.valueof('Test String'); // Can use Mock Http here
            }
           
            return retFile;
        }

    This Apex method will convert the attachment URL to a blob. Not only email attachments but this method can be used to convert any external link (that is of a file) to a blob and then eventually a Salesforce file.

    Now, we have to convert this blob into a Content Version.

    global contentVersion createContentVerion(blob fileContent, String recordId, String filename, Id recordTypeId)
        {
            ContentVersion cv = new ContentVersion();
            cv.ContentLocation = 'S';
            cv.VersionData = fileContent;
            cv.Title = filename+'.pdf';
            cv.PathOnClient = filename+'.pdf';
            cv.RecordTypeId = recordTypeId;
         	return cv;   
        }

    Once, we have the ContentVersion, we can create a ContentDocumentLink that will connect our newly made file with any record we want. In order to create ContentDocumentLink, we will need ContentDocumentId and LinkedEntityId. The ContentDocumentId can be retrieved from the ContentVersion object, while the latter is the record id of an eligible standard or custom object.

    We hope this guide will help you in creating a file from an email attachment in Salesforce. Feel free to leave a comment in case of any queries.

    Talha Saqib
    Talha Saqib
    Founder of Retrology. Been actively following the gaming and media industry for the past 15 years. Also, a full-time software engineer. My day-to-day tasks include writing, editing, strategizing content, managing my team, and handling the complete back-end.

    1 COMMENT

    Subscribe
    Notify of
    guest
    1 Comment
    Oldest
    Newest Most Voted
    Inline Feedbacks
    View all comments