We have a functionality to create leads out of Emails. To do this we have a custom class in which we extract the details of the customer from the inbound email and add the email as an attachment. This has been working for over a year now and keeping in line with direction that salesforce is taking we are trying to move away from attachments and towards using Content Files. I have replaced the existing piece of code for creating attachments with the below code. I see the file is created and linked to the lead. However, when i download it by saving it as an HTML file, the file opens up with binary text. Is there something that I am doing wrong?
public void linkAttachmentsToLead(Id leadId, Messaging.inboundEmail email) {
Blob Body;
if(email.htmlBody != null) {
Body = Blob.valueOf(email.htmlBody);
}
else {
Body = Blob.valueOf(email.plainTextBody);
}
if(email.textAttachments != null) {
for (Messaging.Inboundemail.TextAttachment textAttachment : email.textAttachments) {
Body = Blob.valueOf(textAttachment.body);
}
}
if(email.binaryAttachments != null) {
for (Messaging.Inboundemail.BinaryAttachment binaryAttachment : email.binaryAttachments) {
Body = binaryAttachment.body;
}
}
ContentVersion cv = new ContentVersion();
cv.ContentLocation = 'S';
cv.VersionData=Body;
cv.Title = email.Subject;
cv.PathOnClient = email.Subject;
insert cv;
ContentDocumentLink cdl = new ContentDocumentLink();
cdl.ContentDocumentId = [SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id =: cv.Id].ContentDocumentId;
cdl.LinkedEntityId = leadId;
cdl.ShareType = 'I';
insert cdl;
}