function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
vamshi kothakapu 9vamshi kothakapu 9 

Send email failed: REQUIRED_FIELD_MISSING, Add a recipient to send an email.: [] Class.AccTaskTrigr.AccountTaskTrigger: line 38 column 1

Hi to all,

I am a newbee here having problem to ececute a scenario from my institution.
When  a new Account record is inserted check wheather any duplicate Account exists based on Account Name,Industry  if duplicate record found throw error message. if duplicate records are notfound, check if type=Prospect, if so Create new Task  for the owner of the  account record and send email alert regarding new task. I have no idea ,I have put the toaddress but it is asking for receipent.
Above is the error when i tried to insert account.  and my code with class and trigger are
Trigger:trigger AccTaskTrigr on Account (After insert ) {   // Trigger code is good
    AccTaskTrigr.AccountTaskTrigger(Trigger.New);}  
class:
public class AccTaskTrigr {
    public static void AccountTaskTrigger(List<Account> newtrigger){
      
            List<Task> ListTasks =  new List<Task>();
           Task tsk =new task();
          Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        list<account> accs =[select Name, Industry from Account];
        
            For(account account1:  newtrigger){
            for(account a :accs){
                if(a.name!=account1.name && a.Industry !=account1.Industry){
                    if( account1.Type=='Prospect'){
                    tsk.OwnerId=account1.OwnerId;
                    tsk.Priority='High';
                    tsk.Subject='Email';
                    tsk.Status='In Progress';
                    tsk.WhatId=account1.Id;
                    listTasks.add(tsk);
                   List<user> toAdd=new List<user>();
                        list<string> toadd1 =new List<string>();
                    toAdd =([select user.email from user where user.id=:account1.Ownerid]);
                        for (user u: toadd){
                            toadd1.add(u.email);
                        }
                    mail.setToAddresses(toAdd1);
                    mail.setSubject('Attachments');
                    mail.setPlainTextBody('Test Message');
                    /*EmailTemplate emailt=[Select id from EmailTemplate where name = 'Account_Task_trigger'];
                    mail.setTargetObjectIds(listids);
                    mail.setSenderDisplayName('Vamshi Kothakapu SFDC');
                    mail.setTemplateId(emailt.id);
                    mail.setSaveAsActivity(false);*/
                    }}
                else{ account1.adderror('another account exists with values of name&Industry');}
                }
    }insert listTasks;
    Messaging.Email[] emails=new Messaging.Email[]{mail};
        Messaging.sendEmail(emails); ////Error line 38 is here
    } 
}
 
Best Answer chosen by vamshi kothakapu 9
Amit Chaudhary 8Amit Chaudhary 8
Hi vamshi kothakapu 9,

I found below issue in your code.
1) Need to add all account record in Query . Add filter in query and fatch only selected record.
list<account> accs =[select Name, Industry from Account];
2) Why for loop inside for loop. If you have 100 old record and you are inserting one new record then it will create muliple task record if you filter match
if(a.name!=account1.name && a.Industry !=account1.Industry){

3) You can create workflow to send email on task creation. Simple create task and send email by workflow with the help of email alert.
4) SOQL inside for loop is not best pratice
For(account account1:  newtrigger)
			{
				for(account a :accs)
				{
					if(a.name!=account1.name && a.Industry !=account1.Industry)
					{
						if( account1.Type=='Prospect'){
							tsk.OwnerId=account1.OwnerId;
							tsk.Priority='High';
							tsk.Subject='Email';
							tsk.Status='In Progress';
							tsk.WhatId=account1.Id;
							listTasks.add(tsk);
							List<user> toAdd=new List<user>();
							list<string> toadd1 =new List<string>();
							toAdd =([select user.email from user where user.id=:account1.Ownerid]);

Try to update your code like below
 
public class AccTaskTrigr 
{
    public static void AccountTaskTrigger(List<Account> newtrigger)
    {
		List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
		Set<String> setName = new Set<String>();
		Set<String> setIndustory = new Set<String>();
		Set<String> setAccId = new Set<String>();
		For( Account acc : newtrigger)
		{
			setAccId.add(acc.id);
			if(acc.name != null)
			{
				setName.add(acc.name);
			}
			if (acc.Industry != null)
			{
				setIndustory.add(acc.Industry);
			}
		}
		
		List<Account> lstExsistingAcc = [select id,name,Industry from Account where in not in :setAccId and name in :setName and Industry in :setIndustory];
		Map<String,Account> mapAccount = new Map<String,Account>();
		for(Account acc : lstExsistingAcc)
		{
			if(acc.name != null && acc.Industry!= null)
			{
				String key = acc.name +'-'+acc.Industry;
				mapAccount.put(key,acc);
			}
		}

		List<string> toadd1 =new List<string>();
		toadd1.add(userInfo.getUserEmail()); // Current user will owner by default
		
		For(account acc:  newtrigger)
		{
			if(acc.name != null && acc.Industry != null)
			{
				String key = acc.name +'-'+acc.Industry;
				if( ! mapAccount.containsKey(key))
				{	
					if( acc.Type=='Prospect' )
					{
						tsk.OwnerId=account1.OwnerId;
						tsk.Priority='High';
						tsk.Subject='Email';
						tsk.Status='In Progress';
						tsk.WhatId=account1.Id;
						listTasks.add(tsk);
						
						Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
						mail.setToAddresses(toAdd1);
						mail.setSubject('Attachments');
						mail.setPlainTextBody('Test Message');
						
						mails.add(mail);

					}
				}
				else{
					acc.adderror('another account exists with values of name&Industry');
				}
			}	
		}
		if(listTasks.size() > 0 )
		{
			insert listTasks;
			Messaging.sendEmailResult[] r= Messaging.sendEmail(mails);
		}
	}	
}
http://amitsalesforce.blogspot.com/2015/11/singleemailmessage-vs-massemailmessage.html

Let us know if this will help you
 

All Answers

Rahul KumarRahul Kumar (Salesforce Developers) 
Hi vamshi kothakap,

Please  may I request you to please refer the below link

https://salesforce.stackexchange.com/questions/118857/sendemail-failed-required-field-missing-missing-targetobjectid-with-template/118876#118876

I hope it will be helpful.

Best Regards
Rahul Kumar

 
vamshi kothakapu 9vamshi kothakapu 9
Hi rahul,
thanks but not useful.


Please anyone help me get this done, check my code and hind me get it right.
I have modified the code amny times changing the if else loops, but in vain.

 
Amit Chaudhary 8Amit Chaudhary 8
Hi vamshi kothakapu 9,

I found below issue in your code.
1) Need to add all account record in Query . Add filter in query and fatch only selected record.
list<account> accs =[select Name, Industry from Account];
2) Why for loop inside for loop. If you have 100 old record and you are inserting one new record then it will create muliple task record if you filter match
if(a.name!=account1.name && a.Industry !=account1.Industry){

3) You can create workflow to send email on task creation. Simple create task and send email by workflow with the help of email alert.
4) SOQL inside for loop is not best pratice
For(account account1:  newtrigger)
			{
				for(account a :accs)
				{
					if(a.name!=account1.name && a.Industry !=account1.Industry)
					{
						if( account1.Type=='Prospect'){
							tsk.OwnerId=account1.OwnerId;
							tsk.Priority='High';
							tsk.Subject='Email';
							tsk.Status='In Progress';
							tsk.WhatId=account1.Id;
							listTasks.add(tsk);
							List<user> toAdd=new List<user>();
							list<string> toadd1 =new List<string>();
							toAdd =([select user.email from user where user.id=:account1.Ownerid]);

Try to update your code like below
 
public class AccTaskTrigr 
{
    public static void AccountTaskTrigger(List<Account> newtrigger)
    {
		List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
		Set<String> setName = new Set<String>();
		Set<String> setIndustory = new Set<String>();
		Set<String> setAccId = new Set<String>();
		For( Account acc : newtrigger)
		{
			setAccId.add(acc.id);
			if(acc.name != null)
			{
				setName.add(acc.name);
			}
			if (acc.Industry != null)
			{
				setIndustory.add(acc.Industry);
			}
		}
		
		List<Account> lstExsistingAcc = [select id,name,Industry from Account where in not in :setAccId and name in :setName and Industry in :setIndustory];
		Map<String,Account> mapAccount = new Map<String,Account>();
		for(Account acc : lstExsistingAcc)
		{
			if(acc.name != null && acc.Industry!= null)
			{
				String key = acc.name +'-'+acc.Industry;
				mapAccount.put(key,acc);
			}
		}

		List<string> toadd1 =new List<string>();
		toadd1.add(userInfo.getUserEmail()); // Current user will owner by default
		
		For(account acc:  newtrigger)
		{
			if(acc.name != null && acc.Industry != null)
			{
				String key = acc.name +'-'+acc.Industry;
				if( ! mapAccount.containsKey(key))
				{	
					if( acc.Type=='Prospect' )
					{
						tsk.OwnerId=account1.OwnerId;
						tsk.Priority='High';
						tsk.Subject='Email';
						tsk.Status='In Progress';
						tsk.WhatId=account1.Id;
						listTasks.add(tsk);
						
						Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
						mail.setToAddresses(toAdd1);
						mail.setSubject('Attachments');
						mail.setPlainTextBody('Test Message');
						
						mails.add(mail);

					}
				}
				else{
					acc.adderror('another account exists with values of name&Industry');
				}
			}	
		}
		if(listTasks.size() > 0 )
		{
			insert listTasks;
			Messaging.sendEmailResult[] r= Messaging.sendEmail(mails);
		}
	}	
}
http://amitsalesforce.blogspot.com/2015/11/singleemailmessage-vs-massemailmessage.html

Let us know if this will help you
 
This was selected as the best answer
vamshi kothakapu 9vamshi kothakapu 9
Thanks a Lot Amit, for the code. Now I got belief that someone from nowhere can save me at times through this forums.
I found upper case and lower case were accepting as different accounts but I figured it out and fixed it. Thanks.