I am getting this error message Too many query rows 500001. My trigger creates a task each time an email message is sent with a WhoID based on the personal or work email fields of a contact, are there any steps I can take to lock it down.
Hope it helps,
trigger EmailToTask on EmailMessage (after insert) {
list<Task> lstTask = new list<Task>();
map<String,Id> mapEmail = new map<String,Id>();
for(Contact con: [SELECT Id,Email,npe01__WorkEmail__c,npe01__HomeEmail__c FROM Contact]){
if(string.isNotBlank(con.Email))
mapEmail.put(con.Email,con.Id);
if(string.isNotBlank(con.npe01__WorkEmail__c))
mapEmail.put(con.npe01__WorkEmail__c,con.Id);
if(string.isNotBlank(con.npe01__HomeEmail__c))
mapEmail.put(con.npe01__HomeEmail__c,con.Id);
}
for (EmailMessage e : Trigger.new) {
if (e.RelatedToId != NULL
&& (mapEmail <> NULL && !mapEmail.isEmpty())
) {
Task t = new Task();
t.ActivityDate = date.today();
t.Description = e.TextBody;
t.Move_Type__c = 'Personal Note/Email from Donor';
t.Priority = 'Normal';
t.Status = 'Completed';
t.Subject = e.Subject;
t.WhatId = e.RelatedToId;
if(mapEmail.containsKey(e.ToAddress)){
t.WhoId = mapEmail.get(e.ToAddress);
}
lstTask.add(t);
}
}
if(lstTask <> NULL && !lstTask.isEmpty()){
insert lstTask;
}}