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
Guisselle MartinezGuisselle Martinez 

how can I query for all emails related to an opportunity

From my controller, I need the retrieve all emails related to an specific opportunity.
I noticed when I create a new event as an email, I can grab it from the event object.
But that is an event, I'm looking for the actual email
I'm new to salesforce, so any help will be greatly appreciated!
Gian Piere VallejosGian Piere Vallejos
The email that you want to grab belongs to a Contact that is related to the Account related to the Opportunity. You need to query the AccountIds and then the Contact's email.
You can use this code:
String opportunityId = '';
List <Opportunity> opps = [SELECT AccountId FROM Opportunity WHERE Id = :opportunityId];
Set <Id> accIds = new Set <Id> ();
for (Opportunity opp : opps) {
    accIds.add(opp.AccountId);
}
List <Contact> cts = [SELECT Email FROM Contact WHERE AccountId IN :accIds];
for (Contact ct : cts) {
    System.debug(ct.Email);
}
Let me know if that's what you are looking for.
Guisselle MartinezGuisselle Martinez
Your answer is perfect, thanks!!
Gian Piere VallejosGian Piere Vallejos
Awesome! Please mark it as best answer :)
All the best for you!