When working with Microsoft Dynamics 365 Business Central, automating email communication can save time and ensure consistency. One common requirement for businesses is to automatically add a BCC (Blind Carbon Copy) address when sending out specific documents, such as Sales Invoices. This ensures that a copy of all outgoing invoices is sent to a predefined email address (for audit, compliance, or internal tracking purposes).
In this blog, I’ll walk through how we can achieve this using an event subscriber in AL.
Business Requirement
Whenever a user sends an email for a Sales Invoice document from Business Central, the system should automatically add a BCC email address. The address should be configured in the Sales & Receivables Setup page, so it can be managed by users without modifying the code.
Solution Approach
We use the OnBeforeSendEmail
event in the Document-Mailing
codeunit. This event is triggered just before the email is sent, giving us a chance to customize the email content.
Our enhancement will:
- Identify if the email relates to a Sales Invoice.
- Retrieve the BCC address from Sales & Receivables Setup.
- Append the BCC address to the email item.
AL Code Implementation
[EventSubscriber(ObjectType::Codeunit, Codeunit::"Document-Mailing", 'OnBeforeSendEmail', '', false, false)]
local procedure OnBeforeSendEmail(var TempEmailItem: Record "Email Item" temporary; var IsFromPostedDoc: Boolean; var PostedDocNo: Code[20]; var HideDialog: Boolean; var ReportUsage: Integer; var EmailSentSuccesfully: Boolean; var IsHandled: Boolean; EmailDocName: Text[250]; SenderUserID: Code[50]; EmailScenario: Enum "Email Scenario")
var
SourceTables: List of [Integer];
SourceIDs: List of [Guid];
SourceRelationTypes: List of [Integer];
tableId: Integer;
BCCText: Text[250];
SalesSetup: Record "Sales & Receivables Setup";
begin
TempEmailItem.GetSourceDocuments(SourceTables, SourceIDs, SourceRelationTypes);
foreach tableId in SourceTables do begin
if tableId = Database::"Sales Invoice Header" then begin
SalesSetup.GetRecordOnce();
if SalesSetup."Sales Email BCC_NMX" = '' then exit;
// Add BCC
BCCText := SalesSetup."Sales Email BCC_NMX";
if TempEmailItem."Send BCC" <> '' then begin
if StrLen(TempEmailItem."Send BCC" + ';' + BCCText) < 250 then
TempEmailItem."Send BCC" := TempEmailItem."Send BCC" + ';' + BCCText;
end else begin
TempEmailItem."Send BCC" := BCCText;
end;
Exit;
end;
end;
end;
Key Points
Source Document Check: We verified the document type using SourceTables
to ensure the logic applies only to Sales Invoice.
Event Subscriber: We subscribed to OnBeforeSendEmail
to intervene just before the system sends the email.
Configuration Driven: The BCC address is picked from Sales & Receivables Setup, making it flexible for business users.
Safety Check: We ensured that the total BCC string length does not exceed the field’s max length (250 characters)
Subscribe! so you wont miss latest posts...