rspec/rules/S5498/apex/rule.adoc
Fred Tingaud d3cfe19d7e
Fix broken or dangerous backquotes
Co-authored-by: Marco Borgeaud <89914223+marco-antognini-sonarsource@users.noreply.github.com>
2023-10-30 10:33:56 +01:00

79 lines
2.1 KiB
Plaintext
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

== Why is this an issue?
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++``.
This rule raises an issue when a call to ``++Messaging.sendEmail++`` is found in a loop.
 
=== Noncompliant code example
[source,apex]
----
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
}
}
----
=== Compliant solution
[source,apex]
----
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 });
}
----
== Resources
* https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_gov_limits.htm[Execution Governors and Limits]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== 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.
endif::env-github,rspecator-view[]