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
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

  • Thanks Ronnie. There seems to be an issue with the syntax (line 11) - Compile Error: Missing ';' at 'email'. – TheMikeyBoosh Oct 25 '17 at 1:22
  • Oops, i typed. - instead of = I'll edit. – Ronnie Oct 25 '17 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 Oct 25 '17 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 – TheMikeyBoosh Oct 25 '17 at 3:42
  • so add all of the emails to the array as strings in a for loop – Ronnie Oct 26 '17 at 1:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.