I am sending related attachments from an email message to an external api but the files arrive damaged.

I have tried with other files from other sources but it doesn't work in salesforce.

Here is the code I have:

// Obtener los ContentDocumentLinks relacionados con el EmailMessage
List<ContentDocumentLink> contentDocumentLinks = [SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId IN (SELECT Id FROM EmailMessage WHERE ParentId = '500Ek000005P6x2IAC')];

// Crear una lista de Ids de ContentDocument
List<Id> contentDocumentIds = new List<Id>();
for (ContentDocumentLink link : contentDocumentLinks) {

// Obtener los ContentVersions asociados a los ContentDocuments
List<ContentVersion> contentVersions = [SELECT VersionData, FileType, Title, FileExtension FROM ContentVersion WHERE ContentDocumentId IN :contentDocumentIds];
String boundary = '----WebKitFormBoundary' + String.valueOf(Crypto.getRandomInteger());
String requestBody = '';

// Crear una solicitud HTTP
HttpRequest req = new HttpRequest();
req.setHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);

// Agregar cada archivo al cuerpo de la solicitud
for (ContentVersion cv : contentVersions) {
    requestBody += '--' + boundary + '\r\n';
    requestBody += 'Content-Disposition: form-data; name="file"; filename="' + cv.Title + '.' + cv.FileExtension + '"\r\n';
    requestBody += 'Content-Type: application/octet-stream\r\n\r\n';
    requestBody += EncodingUtil.base64Encode(cv.VersionData) + '\r\n';


// Agregar el pie de página al cuerpo de la solicitud
requestBody += '--' + boundary + '--\r\n';

// Establecer el encabezado de Content-Type con el límite de multipart/form-data

// Crear una instancia de HTTP para enviar la solicitud
Http http = new Http();
HttpResponse res = http.send(req);

// Procesar la respuesta si es necesario
if (res.getStatusCode() == 200) {
    // Éxito
    System.debug('Solicitud enviada exitosamente.');
} else {
    // Error
    System.debug('Error al enviar la solicitud. Código de estado: ' + res.getStatusCode());
  • VersionData is already in Base64 so you don't need to encode it, see documentation. Commented Feb 8 at 5:28
  • @DavidCheng Just add the field and it returns me this path /services/data/v56.0/sobjects/ContentVersion/068Ek0000016ESjIAM/VersionData and the file weighs 1kb Commented Feb 8 at 18:32
  • @identigral The sending works but I think I am wrong when sending the VersionData. I think I should attach another class instead of ContentVersion Commented Feb 8 at 18:34
  • I don't know what you mean when you say "add the field" and you mention the file size. I'm saying that you don't need to use EncodingUtil.base64Encode() because VersionData is already encoded as Base64. Commented Feb 8 at 21:30
  • Please see the related Q&A I linked. The data is being damaged by base64 encoding, which is the fault of the code here. You need to send the data in binary form. Apex doesn't make this easy. Alternatively, you can try adding the Content-Transfer-Encoding: base64 header for the form element headers, but not all servers support this syntax.
    – sfdcfox
    Commented Feb 9 at 13:09


Browse other questions tagged .