+ Start a Discussion
woodmanzeewoodmanzee 

Can't send email message from Messaging.SingleEmailMessage- everything looks alright

Don't know what the issue is, i've checked other sources and everything looks like it should be just fine but my code is throwing an exception rather than sending the email. I've kind of reached my limit and can't figure it out. 

 

public PageReference Send() {
    
        List<Opportunity> opps = [SELECT Id, Name, Client_Name__c, Responsible_Party__c, Email_for_Survey__c, First_Name_of_Survey_Recipient__c FROM Opportunity WHERE Id =: ApexPages.currentPage().getParameters().get('id')];
        Opportunity opp = opps[0];

        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 

        EmailTemplate et = [SELECT id, Name FROM EmailTemplate WHERE Name = 'HH Survey Invitation'];
        mail.setTemplateID(et.Id);
        
        String[] toAddresses = new String[] {email};
        mail.setToAddresses(toAddresses);
        
        mail.setSaveAsActivity(false);
        mail.setTargetObjectId(opp.Id);
 
        try {
            //mail.setWhatId(opp.Id);
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
            //createLog(opp.Id);
        } catch(Exception e) {
            error = toAddresses[0] + ' ' + et.Name + ' ' + opp.Name;
            return null;
        }
        
        PageReference detail = new PageReference('/' + opp.Id);
        detail.setRedirect(true);
        return detail;
        
    }

 

I know the template is valid, the opportunity is valid, and so is the email address. Anything I'm missing? Thanks in advance

woodmanzeewoodmanzee

Or another bit of info that might be helpful - if I set an Opportunity Id as the targetObjectId, what email address is it using to send the email to?

Vinit_KumarVinit_Kumar

Hi Woodmazee,

 

In setTargetObjectId you can only have either contact,lead or User.It can't have opportunity id.Please find below the link which confirms the same.

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_email_outbound_single.htm