public class SendMail {
public static void function(){
Date tenDays = date.Today().addDays(10);
List<opportunity> oppList = [SELECT Name, AccountId FROM Opportunity WHERE AccountId != NULL AND closeDate =: tenDays];
Set<id> data = new Set<id>();
for(opportunity opp: oppList){
data.add(opp.AccountId);
}
List<contact> conList = [SELECT Name, Email FROM Contact WHERE AccountId IN :data AND email != null];
List<String> emails = new List<String>();
for(contact con : conList){
emails.add(con.email);
}
System.debug(emails);
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses(emails);
email.setSubject('This is subject');
email.setPlainTextBody('This is body');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
}
}
If you find the above code helpful, please mark it as best answer. Thank you.
Please try with the below code and let me know further :
public class OpportunityEmailSender {
public static void sendOpportunityDetailsToContacts() {
// Get the current date and calculate the close date 10 days later
Date today = Date.today();
Date closeDate = today.addDays(10);
// Query the opportunities with the specified close date and related account and contacts
List<Opportunity> opportunities = [
SELECT Id, Name, CloseDate, AccountId, Account.Name,
(SELECT Id, Name, Email FROM Contacts)
FROM Opportunity
WHERE CloseDate = :closeDate
];
// Iterate over the opportunities and send emails to the contacts
for (Opportunity opp : opportunities) {
List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
for (Contact con : opp.Account.Contacts) {
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses(new List<String>{con.Email});
email.setSubject('Opportunity Details: ' + opp.Name);
email.setPlainTextBody('Opportunity Name: ' + opp.Name +
'\nClose Date: ' + opp.CloseDate +
'\nAccount Name: ' + opp.Account.Name +
'\nContact Name: ' + con.Name +
'\nContact Email: ' + con.Email);
emails.add(email);
}
// Send the emails
Messaging.sendEmail(emails);
}
}
}
Apex Code is below:
If you find the above code helpful, please mark it as best answer.
Thank you.
Please try with the below code and let me know further :
Hope this helps !
Thank you