0

I understand that visualforce templates cannot be mass emailed. Is it possible to put a single email method in a loop? I also understand that lists in loops are bad!

I have tried to cut up this post to suit the requirement.

APEX:

public PageReference sendEmail(){   

ID currentRecordID = ApexPages.CurrentPage().getparameters().get('ID');
emailTemplate et = [Select id from EmailTemplate where name = 'ABS Trainer - Unit Confirmation - Online' LIMIT 1];

List<Contact> contactNames = [SELECT id, name FROM Contact WHERE AccountId =: currentRecordID LIMIT 200];
    for (String obj : contactNames){
        contact = [SELECT Id,name,email FROM Contact WHERE name =:obj];
        for(Integer i=0; i < contact.size(); i++){
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            email.setTargetObjectId(contact[i].Id);
            email.setTemplateId(et.id);
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
        }  
    }
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Email Sent Successfully'));
return null;
}

1 Answer 1

-1
EmailTemplate et = [ SELECT Id FROM EmailTemplate WHERE Name =: 'ABS Trainer - Unit Confirmation - Online' LIMIT 1 ];
List<Contact> contacts = [ SELECT Id, Name, Email FROM Contact WHERE AccountId =: currentRecordId LIMIT 200 ];
Set<String> addresses = new Set<String>();

for( Contact c : contacts ){
    if( !addresses.Contains( c.Email ) ){ addresses.Add( c.Email ); }
}

string[] toAddresses = new string[ addresses.size() ];

Integer i = 0;
for( String address : addresses ){
    toAddresses[ i ] = address;
    i++;
}

Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses( toAddresses );
email.setTemplateId( et.Id );
Messaging.sendEmail( new Messaging.SingleEmailMessage[]{ email } );

try this!

Add your to addresses to an array and send the template to this array of Contact Email Addresses

8
  • Thanks Ronnie. There seems to be an issue with the syntax (line 11) - Compile Error: Missing ';' at 'email'. Commented Oct 25, 2017 at 1:22
  • Oops, i typed. - instead of = I'll edit.
    – Ronnie
    Commented Oct 25, 2017 at 3:33
  • Response updated, easy slip of the finger, should have been easy to figure out on your end looking at that line. Should be good to go now.
    – Ronnie
    Commented Oct 25, 2017 at 3:34
  • Thanks for updating your answer. There is a new error - Compile Error: Initial expression is of incorrect type, expected: String but was: Set<String> at line 8 Commented Oct 25, 2017 at 3:42
  • so add all of the emails to the array as strings in a for loop
    – Ronnie
    Commented Oct 26, 2017 at 1:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .