Create a trigger to create a task when account is created, associate the created task to the account and send a email to notify the owner that account and task has been created. Below is the code but i am hitting below error
Apex trigger CreateTaskAssociatedWithAccount caused an unexpected exception, contact your administrator: CreateTaskAssociatedWithAccount: execution of AfterInsert caused by: System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_EMAIL_ADDRESS, Email address is invalid: User:{[email protected], Id=0055g00000Bze7aAAB}: [toAddresses, User:{[email protected], Id=0055g00000Bze7aAAB}]: Trigger.CreateTaskAssociatedWithAccount: line 34, column 1
Please forgive my bad coding methods I am trying my best.
Trigger CreateTaskAssociatedWithAccount on Account(after Insert){
List<Task> createtask = new List<Task>();
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
for(Account acc: trigger.new){
//Create task record
Task t = new Task();
t.subject = 'Account Created :' + acc.Name;
t.whatId = acc.Id;
t.OwnerId = acc.OwnerId;
t.ActivityDate = date.today();
t.Status = 'Not Started';
createtask.add(t);
//Send Email Notification
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
list<user> sentTo = [Select Email From User where Id =: acc.OwnerId];
Map<Id,String> userEmail = new Map<Id,String>();
for(User a : sentTo){
userEmail.put(a.Id, string.valueof(a));
}
mail.setToAddresses(userEmail.values());
mail.setSubject('New Account and a Task related to it are created');
String body = 'A new Account ' + acc.id + '& a new Task has been created';
mail.setHTMLBody(body);
mails.add(mail);
}
insert createtask;
Messaging.sendEmail(mails);
}