• David Bingham 12
  • NEWBIE
  • 0 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies
I want to send an email and create a new record for a custom object, lda_Request__c. If there is an attachment on the email, i want it to be associated with the new record. The code below is 100% covered and tests appear to create the ContentVersion object, but when I send a real email with a real attachment, the new record is created, but there is no sign of the new ContentVersion record nor the ContentDocumentLink record and I get no errors. Can anyone please help?
 
global class ResearchRequestByEmail implements Messaging.InboundEmailHandler {
 
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope env){
        
        // Create an InboundEmailResult object for returning the result of the Apex Email Service
        Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
        
        String PTSubject = '';
        PTSubject = email.subject;
        string myHTMLBody = '';
        myHTMLBody = email.htmlBody;
        
        // Get User Id
        User Apprvr = [SELECT Id, Name FROM User WHERE Email = :email.fromAddress LIMIT 1];
        
        // Create new Request
        lda_Request__c request = new lda_Request__c();
        request.Approver__c = Apprvr.Id;
        request.Request_Subject__c = PTSubject;
        request.Request_Details__c = myHTMLBody;
        request.Via_Email__c = True;
        request.Status__c = 'New';
        request.Property_Description_Method__c = 'Via Email';
        insert request;

        // Attachments using Content Version
        if (email.binaryAttachments != null){
            for (Messaging.InboundEmail.binaryAttachment binAttach :email.binaryAttachments){
                ContentVersion cv = new ContentVersion();
                cv.VersionData = binAttach.body;
                cv.Title = binAttach.fileName;
                cv.PathOnClient = binAttach.fileName;
                //cv.FirstPublishLocationId = request.Id;
                insert cv;
                
                cv = [select ContentDocumentId from ContentVersion where id = :cv.id limit 1];

                ContentDocumentLink cdl = new ContentDocumentLink();
                cdl.LinkedEntityId = request.Id;
                cdl.ContentDocumentId = cv.ContentDocumentId;
                cdl.ShareType = 'V';
                insert cdl;
            }
        }
        result.success = true;
        
        // Return the result for the Apex Email Service
        return result;
    }
}