+ Start a Discussion

Unable to retrieve attachment from activity history in (after insert) trigger

Hi i have a Email-to-Salesforce enabled and will save attachment for every email in activity history. Now i would like query back the attachment but it return 0 result. My trigger as below: 

Trigger TestAtchfromTask on Task (after insert) {
    for(Task tk:Trigger.new){
        List<Attachment> atch = [select Id, Name, Body, BodyLength from Attachment where ParentId =: tk.id];
        System.debug('attachment >> ' + atch);

1.) First thing first ,you are running your query inside for loop which is against the best pratices of salesforce.You should move it outsode the For loop

2.) Can you just check whether Attachment is getting associted to the Task which is being inserted or not on UI coz the query looks good.I would  suggest to go through the debug logs and see the order of execution.
Hi Vinit, 

Thanks for your reply! I am really new in Apex code, if I do not select within the for, how can I retrieve the tk.Id as my SOQL where clause?

The attachment is associalted to the task, when I open the task and it show the attachments. The executioin order is:

1) before insert task, modify some task field
2) after insert task, trying to search the attachments but return list 0

I am assuming that the attachment is geting inserted after the Trigger has been executed,hence query is returning null.That's why I said to check the Debug logs and see when the attachment is getting inserted.

About changing the Query outside the for loop try below :-

Trigger TestAtchfromTask on Task (after insert) {

List<Id> taskIds = new List<Id>();
for(Task tk:Trigger.new)

//Query related attachments
	List<Attachment> atch = [select Id, Name, Body, BodyLength from Attachment where ParentId in: taskIds];