How to create a file from an email attachment in Salesforce

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. This time we are helping 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, and 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 in Salesforce. Following are the points you need to understand:

  • Get the attachment’s URL from the 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.setHeader('Content-Type', 'application/pdf'); 
        Blob retFile;
            HttpResponse res = h.send(req);   // Now Send HTTP Request
            retFile = res.getBodyAsBlob();  // Convert the response into Blob 
            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. To know about How to generate Excel file in Aura Component of Salesforce or for more coding hacks, keep following Salesforce Guides.

Was this helpful?

Thanks for your feedback!

Talha Saqib

About Author

As a Salesforce Certified Developer, Talha Saqib is an expert in designing and implementing custom Salesforce solutions that help businesses achieve their goals. With 3+ years of experience in the Salesforce ecosystem, Talha has a deep understanding of the platform and is expert in Sales Cloud, Service Cloud, Experience Cloud, REST APIs, Aura and more.

Leave a comment

Your email address will not be published. Required fields are marked *

You may also like

Lookup field in Web To Lead form

How to use Lookup field in Web To Lead form in Salesforce

Salesforce’s Web-to-Lead is a great tool to generate leads via HTML forms embedded in any website or app. A Web-to-Lead
find Salesforce org type via Apex Code

How to find Salesforce org type via Apex code?

If we think about it, it’s an interesting problem; To find Salesforce org type via Apex code. There can be