7

I'm creating EmailMessage records via DML

EmailMessage createWhatEmail = new EmailMessage(
     Subject                = 'test'
    ,Status                 = '3'
    ,ToAddress              = 'heim@elastify.eu'
    ,FromAddress            = UserInfo.getUserEmail()
    ,FromName               = UserInfo.getFirstName()+' - '+UserInfo.getLastName()
    ,HtmlBody               = 'a body'
    ,Incoming               = false
    ,MessageDate            = DateTime.now()
    ,RelatedToId            = taskWhatId
    // ,HasAttachment       = true // not possible: Read-Only!
);
insert createWhatEmail;

The attachments I'm assigning like this:

for(ContentVersion cv : attachmentCVs) {
    ContentDocumentLink cdl = new ContentDocumentLink(
         ContentDocumentId  = cv.ContentDocumentId
        ,LinkedEntityId     = createWhatEmail.Id
        ,ShareType          = 'V' 
    );
    attachmentCDLs.add( cdl );
}

But the result is not flawless:

enter image description here

The attachment is shown correctly under the Attachments related list. But the non-writable HasAttachment field is false. Hence the paper-clip indicating the attachment isn't show in the Activity Tab under LEX.

Does anyone know a way to make this right?

The result should look more like this:

enter image description here

  • 1
    I somehow feel this is related to this issue. It though says it was fixed in Summer '18. – Jayant Das Jul 12 '18 at 3:48
  • @JayantDas could be related, but also could be an other bug. Or a feature. Or I'm doing something wrong. I would love to learn more about this. Only thing I can say: the behavior described above is reproducible on all of the org I'm working on. – Uwe Heim Jul 12 '18 at 12:35
  • Did you find a solution? – user1933169 Apr 3 '19 at 17:20
1

I spent close to 4 hours on this and figured it out. The key thing is to populate Attachment.ParentId with EmailMessage Id.

Here is the sample code. Make sure that you have a VF page named "DummyPage" before running the below code:

EmailMessage emailMessage = new EmailMessage();
emailMessage.status = '3'; // email was sent
emailMessage.relatedToId = '001XXXXXXXXXXX'; 
emailMessage.fromAddress = 'billing@acme.com'; // from address
emailMessage.fromName = 'Billing Department'; // from name
emailMessage.toAddress = 'johnSmith@example.com';
emailMessage.Subject = 'Hello';

emailMessage.HtmlBody = 'Hello World';
insert emailMessage;

Pagereference dummyPage = Page.DummyPage;
Blob blobObj = dummyPage.getContentAsPDF();

Attachment obj = new Attachment();
obj.Body = blobObj;
obj.ParentId = emailMessage.Id;
obj.Name = 'Dummy.pdf';
obj.ContentType = 'application/pdf';
insert obj;

System.debug([SELECT Id,HasAttachment FROM EmailMessage WHERE Id =: emailMessage.Id]);
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.