2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-10-30 10:33:56 +01:00
Salesforce Governor Limits do not allow more than 10 calls to ``++Messaging.sendEmail++`` in a single transaction. There is a good chance that calling this method in a loop will reach that limit and fail. You can instead send a batch of emails with a single call to ``++Messaging.sendEmail++``.
2021-04-28 16:49:39 +02:00
This rule raises an issue when a call to ``++Messaging.sendEmail++`` is found in a loop.
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,apex]
2021-04-28 16:49:39 +02:00
----
trigger MyWelcomeTrigger on Contact (after insert) {
List<Id> toIds = new List<Id>();
for (Contact contact : trigger.new)
{
if(contact.Email != null)
{
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] { contact.email };
mail.setToAddresses(toAddresses);
mail.setSubject('Welcome');
mail.setPlainTextBody('Welcome');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); // Noncompliant
}
}
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,apex]
2021-04-28 16:49:39 +02:00
----
trigger MyWelcomeTrigger on Contact (after insert) {
List<Id> toIds = new List<Id>();
for (Contact contact : trigger.new)
{
if(contact.Email != null)
{
toIds.add(contact.Id);
}
}
string templateName = 'Welcome Email Template';
EmailTemplate template = [select Id, Name from EmailTemplate where name = :templateName];
Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
mail.setTargetObjectIds(toIds);
mail.setTemplateId(template.Id);
Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });
}
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
== Resources
2021-04-28 16:49:39 +02:00
* https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_gov_limits.htm[Execution Governors and Limits]
2021-04-28 18:08:03 +02:00
2021-09-20 15:38:42 +02:00
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
Send these emails in batch
=== Highlighting
Primary Location: the call to "Messaging.SendEmail"
Secondary Location: the "do", "while" or "for" keyword of the loop.
2021-09-20 15:38:42 +02:00
endif::env-github,rspecator-view[]