+ Start a Discussion

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'];
        String[] toAddresses = new String[] {email};
        try {
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
        } catch(Exception e) {
            error = toAddresses[0] + ' ' + et.Name + ' ' + opp.Name;
            return null;
        PageReference detail = new PageReference('/' + opp.Id);
        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


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?


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.