You can send emails programmatically in Apex, but if you’re not careful you can hit the measly governor limit of 10 in no time at all. You see, although your outbound email limit is 1000 with Apex, only a total of 10 sendEmail method calls are allowed in each context.
Obviously the way to avoid this is to gather up all emails you want to send and call the sendEmail method once from your Apex context. When passing an argument to the sendEmail method it must be of type Email. However, in order for each email to be a unique, (assuming you want that), they need to be of type SingleEmailMessage. If you don’t desire uniqueness, you may use the MassEmailMessage type. These objects all belong to a native Apex class called Messaging.
Let’s go through some code to illustrate some techniques –
Messaging.SingleEmailMessage [] theEmails = new List();
for( Integer i = 0; i < numberOfSeparateEmails; i++ ){
String[] toAddress = new List(); // setToAddresses will only accept a List (array)
toAddress.add(bunchOfAddresses.get(i));
String subjectTag = bunchOfSubjectTags.get(i);
String msgBody = bunchOfMsgBodys.get(i);
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses( toAddress ); // only takes a List (array) as noted above
mail.setReplyTo( replyAddress );
mail.setSenderDisplayName(’My Company Email’);
mail.setSubject(subjectTag);
mail.setPlainTextBody( msgBody );
theEmails.add(mail);
}
Now let’s populate an array of Email objects with each of our SingleEmailMessage objects.
Note: you can’t just pass the full SingleEmailMessage array. You MUST add each element separately.
for( Integer j = 0; j < theMails.size(); j++ ){
allMails.add(theMails.get(j));
}
Now we can make the sendEmail call and pass in the array of Email objects
Always good to check for errors. So we use the object SendEmailError’s methods and build a little report (String)
for( Messaging.SendEmailResult currentResult : results ) {
errors = currentResult.getErrors();
if( null != errors ) {
for( Messaging.SendEmailError currentError : errors ) {
emailErrorReport = emailErrorReport + ‘(’ + currentError.getStatusCode() + ‘) ‘ + currentError.getMessage() + ‘\r’ ;
}
}
}
Well that’s one way to handle the programmatic sending of email in Apex.
Hope it makes your cloud computing less cloudy ~ ~ ~
Related posts:
- The User, Visualforce and Apex — about a drop down menu Let’s say you coded a custom view or report using...
- Setting Lead Assignment Rules with Apex If you want to create a new Lead via Visualforce...
Related posts brought to you by Yet Another Related Posts Plugin.











Posted by tburre on July 24, 2009 at 2:12 am
