My People are trying to use a custom button in order to send an Email from a VF Page. On click of send button, send method of the Controller Class is called to send an Email.
public PageReference send() {
try {
Messaging.SingleEmailMessage singleEmailMsg = new Messaging.SingleEmailMessage();
singleEmailMsg.setTargetObjectId(emailMsg.ToIds[0]); // This line is causing the System.ListException: List index out of bounds: 0
if (emailMsg.BccAddress != null && emailMsg.BccAddress != '') {
singleEmailMsg.setBccAddresses(emailMsg.BccAddress.split(';'));
}
The Constructor:
public SendQuoteEmail_Controller(ApexPages.StandardController controller) {
qtId=ApexPages.currentPage().getParameters().get('Id');
if(qtId != NULL)
qt = [SELECT Id, Name, Contact_Person__c, Contact_Person__r.Name, Contact_Person__r.Email, Opportunity__r.Id
FROM Quote__c
WHERE Id = :qtId];
ownerId = [Select Id,CreatedById from Quote__c where Id=:qtId].CreatedById;
emailMsg = new EmailMessage();
emailMsg.Subject = 'Quote for Opportunity';
emailMsg.ToIds = new List<Id>{qt.Contact_Person__c}; // This collection is coming out as empty in debug (emailMsg.ToIds.size() = 0)
emailMsg.fromAddress = UserInfo.getUserEmail();
emailMsg.HtmlBody = 'Please find attached the quote';
List<Attachment> lstAttachments = [SELECT Id,Name, Body, ContentType, Bodylength
FROM Attachment
WHERE ParentId = :qt.Id
ORDER BY CreatedDate DESC];
opp = [SELECT Id, Name, Quote_Sent__c
FROM Opportunity__c
WHERE Id = :qt.Opportunity__r.Id];
//Ended
}
}
To my surprise, even though the qt.Contact_Person__c field has a value in it, emailMsg.ToIds[0] throws an exception. Also, emailMsg.ToIds is debugged as empty. What could be causing this?
I'm bit surprised this compiles OK. EmailMessage is a standard object but officially it doesn't have a
toIds
field. Except you can see it used in the example at bottom of the page. Some undocumented mess. Maybe raise case with support.What's the button like? If you have "immediate=true" or apex:actionRegion in there it might be legit not posting back whole viewstate... That
System.debug
comment is about debug from constructor or button click handler?I've hit a subtle bug with emails few weeks ago. it seems that raw access to
ccAddresses
for example is buggy. https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_single.htm said these all should be accessible and your code compiles... I had to usesetCcAddresses()
callYou already have SingleEmailMessage, maybe try explicitly setting
setTargetObjectId(contact id goes here)
?