Below is my batch which sends emails to contacts based on the accounts passed in the scope. I want to mark the date on the Account on which the email has been sent to its contacts. Is there any way I can get all those contacts for which email has been successfully sent so that I can populate the date on the related Account? I have tried to use Messaging.SendEmailResult but it seems we cannot get contact details with this.
global List<Account> start(Database.BatchableContext BC){
List<Account> accountList = Database.query(query);
return accountList;
}
global void execute(Database.BatchableContext bc, List<Account> scope) {
Set<Id> accountIdSet = new Set<Id>();
List<Messaging.SingleEmailMessage> messages = new List<Messaging.SingleEmailMessage>();
for(Account acc : scope){
accountIdSet.add(acc.Id);
}
if(!accountIdSet.isEmpty()){
List<Contact> contactList =
[
SELECT Id, AccountId, Name
FROM Contact
WHERE AccountId IN : accountIdSet
];
if(!contactList.isEmpty()){
for(Contact con : contactList){
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
message.setTargetObjectId(con.Id);
message.setUseSignature(False);
message.setSaveAsActivity(False);
message.setTemplateID('00XXXXXXXXXXX');
message.setWhatId(con.Id);
message.setOrgWideEmailAddressId('00YYYYYYYYYY');
messages.add(message);
}
}
if(!messages.isEmpty()){
Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
for(Messaging.SendEmailResult res : results){
if(res.isSuccess()){
}
}
}
}
}
global void finish(Database.BatchableContext bc) {
}
Any help would be appreciated. Thanks!
successfully sent
means what? not bounced?Messaging.SendEmailResult
only returns errors if theSingleEmailMessage
was malformed