3

I am beginning to write a trigger that grabs an attachment from an Email Message on a Case. Eventually, the goal is to be able to send emails using this trigger, but right now, I am having difficulty organizing the attachments and Ids into a map to properly bulkify. For each unique EmailMessage ID (the Key in the map), I would like to have the Value be a List of attachments (those attachments being ONLY the ones associated with that the particular email message ID in the key. Below is a snippet of what I have started.

trigger hardwareAttachmentEmail on EmailMessage (after insert) {

List<Attachment> allAttachments = New List<Attachment>();
Set<Id> validEmailIds = New Set<Id>();
Map<Id, List<Attachment>> emailMap = New Map<Id, List<Attachment>>();


for (EmailMessage e : Trigger.new) {
    if(e.Parent.RecordTypeId == '01280000000HpXA'){
        validEmailIds.add(e.Id);

    }
}

allAttachments = [SELECT Id, Name, ParentId, Body FROM Attachment WHERE ParentId IN :validEmailIds];



for (Attachment a : allAttachments){
**Here is where I need to set the Map**
}


}

Does it make sense for me to have a nested For loop or to use a different method of accomplishing this? I appreciate any input.

5

The code could look like this:

Map<Id, List<Attachment>> emailMap = new Map<Id, List<Attachment>>();
for (Id id : validEmailIds) emailMap.put(id, new List<Attachment>());
for (Attachment a : [
        SELECT Id, Name, ParentId, Body
        FROM Attachment
        WHERE ParentId IN :validEmailIds
        ) {
    emailMap.get(a.ParentId).add(a);
}

The second line makes sure there is an empty list for each Id, then the main loop can get the list and just add the Attachment to the list.

Note that by querying the Body, you are in danger of exceeding the heap spece limit if the bodies are large (as they can be).

| 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.