# Modify Email Messages

*By following this guide, you'll be able to make the most out of the `OnBeforeSendEmailMessage` in Golden EDI. Have questions? Feel free to reach out!*

### Introduction

The `OnBeforeSendEmailMessage` event has been added to our free PDF atomization functionality in order to allow you to modify e-mails through code right before they are sent over to the standard BC functionality. This event keeps and passes the reference to the source document as a record reference allowing you to lookup any information you need to do the appropriate changes.&#x20;

### Event Signature

In order for you to be able to do the changes you need to the outgoing e-mail we've made sure to add as much information we can to the event. The event has the following signature:

{% code title="GEDI PDF Function" fullWidth="true" %}

```al
procedure OnBeforeSendEmailMessage(var Email: Record "Email Item"; var SelectedScenario: Enum "Email Scenario"; var SourceRef: RecordRef; DocumentNo: Code[50]; var IsHandled: Boolean)
```

{% endcode %}

**Parameters:**

* `Email`: The email item we've created, which will be passed to the standard e-mail handler after the event subscribers are done and `IsHandled` is set to `false`.
* `SelectedScenario`: The e-mail scenario that has been used.
* `SourceRef`: A record reference pointing to the source document that has been used to generate the e-mail and the attached PDF document.
* `DocumentNo`: The document no. for the source document pointed to by the record reference.
* `IsHandled`: Flag to indicate that you've manually handled the e-email and we should not continue to process this e-mail. If set to `true` it will not be passed by us to the standard E-mail functionality.&#x20;

{% hint style="warning" %}
Do not set IsHandled to true unless you manually call the `Send` method on the `Email Item`. Likewise, do not forget to set this to true if you **DO** send the item yourself. Otherwise the recipient will end up with multiple e-mails.&#x20;
{% endhint %}

### Examples

Here you can find a collection of examples on how to utilize this function to modify outgoing e-mails.

#### Change the E-mail Subject

This is an example for how you would build a listener that changes the subject of the e-mail item before being sent to the recipient. This example verifies that the source document is an invoice and then uses the `Sell-to Customer No.` to build a new subject with the customer name and the invoice number.&#x20;

{% code fullWidth="true" %}

```al
[EventSubscriber(ObjectType::Codeunit, Codeunit::"GEDI PDF Function", 'OnBeforeSendEmailMessage', '', true, true)]
local procedure OnBeforeSendEmailMessage(var Email: Record "Email Item"; var SelectedScenario: Enum "Email Scenario"; var SourceRef: RecordRef; DocumentNo: Code[50]; var IsHandled: Boolean)
var
    FldRef: FieldRef;
    CustomerNo: Code[20];
    Customer: Record Customer;
begin
    // Verify that the source is a Sales Invoice Header, since we only want to modify invoice E-mails.
    if SourceRef.Number() = Database::"Sales Invoice Header" then begin
        // Get the Sell-to Customer field.
        FldRef := SourceRef.Field(2);
        CustomerNo := FldRef.Value();

        // Get the customer record for the Sell-to Customer.
        Customer.Get(CustomerNo);

        // Update the subject for the E-mail.
        Email.Subject := StrSubstNo('Hello, %1, here is your invoice %2.', Customer.Name, DocumentNo);
    end;
end;
```

{% endcode %}

#### Change the E-mail Recipient and/or Sender

This example shows you how you can modify either the sender or the recipient e-mail address. For this example we've set a requirement that the document must be an order and then pick the recipient from field "Sell-to E-mail" on the order itself as the recipient if its filled in, leaving it as-is should the field be empty.&#x20;

We also show how to change the "From Address" in the rare cases where you might want to dynamically change this based on some information. For illustrative purposes we only use the e-mail set in "Company Information".&#x20;

{% hint style="danger" %}
Changing the "From Address" requires that the E-mail Account configured in the E-mail Scenario has explicit **Send As** or **Send on Behalf Of** permission for that address - this must be configured in your mail provider (e.g. Exchange/Microsoft 365, SMTP relay).&#x20;

Without these permissions, e-mails will **fail to deliver**. Many providers reject such e-mails **silently and without a bounce notification**, meaning you will receive no error in Business Central and may not discover the problem until much later.
{% endhint %}

{% code fullWidth="true" %}

```
[EventSubscriber(ObjectType::Codeunit, Codeunit::"GEDI PDF Function", 'OnBeforeSendEmailMessage', '', true, true)]
local procedure OnBeforeSendEmailMessage(var Email: Record "Email Item"; var SelectedScenario: Enum "Email Scenario"; var SourceRef: RecordRef; DocumentNo: Code[50]; var IsHandled: Boolean)
var
    FldRef: FieldRef;
    SellToEmailAddress: Code[80];
    CompanyInformation: Record "Company Information";
begin
    // Verify that the source is a Sales Header, since we only want to modify order E-mails.
    if SourceRef.Number() = Database::"Sales Header" then begin
        // Get the Sell-to E-Mail field.
        FldRef := SourceRef.Field(172);
        SellToEmailAddress := FldRef.Value();

        // If the e-mail is set then we switch to this as the recipient of the order confirmation e-mail.
        if SellToEmailAddress <> '' then begin
            Email.Validate("Send to", SellToEmailAddress);
        end;

        // Get the main company e-mail address from the Company Information table and set it as the sender of the e-mail.
        if CompanyInformation.Get() then begin
            Email.Validate("From Address", CompanyInformation."E-mail");
            Email.Validate("From Name", CompanyInformation."Name");
        end;
    end;
end;
```

{% endcode %}

#### Change the Primary E-mail Attachment Name

This example demonstrates how to rename an email attachment. It verifies that the email contains at least one attachment and that the source document is an invoice. The example then uses customer information from the `Sell-to Customer No.` to create a personalized name for the primary PDF attachment.

This technique takes advantage of the fact that attachments are always stored in the same order they are added. Since we always generate and attach the primary document first, it will always be at index 1. Then you will find the incoming documents attached to the invoice (if any) in the same order they are stored in the system, from index 2 and above.&#x20;

{% code fullWidth="true" %}

```al
[EventSubscriber(ObjectType::Codeunit, Codeunit::"GEDI PDF Function", 'OnBeforeSendEmailMessage', '', true, true)]
local procedure OnBeforeSendEmailMessage(var Email: Record "Email Item"; var SelectedScenario: Enum "Email Scenario"; var SourceRef: RecordRef; DocumentNo: Code[50]; var IsHandled: Boolean)
var
    FldRef: FieldRef;
    CustomerNo: Code[20];
    Customer: Record Customer;
    TempBlobList: Codeunit "Temp Blob List";
    FileNames: List of [Text];
    Name: Text;
begin
    // Check that the email contains attachments and the source is an invoice
    if Email.HasAttachments() and (SourceRef.Number() = Database::"Sales Invoice Header") then begin
        // Get the Sell-to Customer field.
        FldRef := SourceRef.Field(2);
        CustomerNo := FldRef.Value();

        // Get the customer record for the Sell-to Customer.
        Customer.Get(CustomerNo);

        // Get the list of all attachments (in attached order, i.e. first is always invoice/credit/report and the rest are "incoming document" attachments)
        Email.GetAttachments(TempBlobList, FileNames);

        // Update the name for the generated report file
        Name := StrSubstNo('Invoice %1 - %2 - %3.pdf', DocumentNo, Customer.Name, Customer.Contact);
        FileNames.Set(1, Name);

        // Replace the attachments with the updated name
        Email.SetAttachments(TempBlobList, FileNames);
    end;
end;
```

{% endcode %}

#### Add a new Attachment to the E-mail

This example explains how to generate a new PDF and attach it to the email. It filters similarly to other examples and generates a sales report for all customers, attaching it to the email with a name specific to the customer. This method allows adding special reports or attachments without altering the standard PDF generation by Golden EDI.

{% code fullWidth="true" %}

```al
[EventSubscriber(ObjectType::Codeunit, Codeunit::"GEDI PDF Function", 'OnBeforeSendEmailMessage', '', true, true)]
local procedure OnBeforeSendEmailMessage(var Email: Record "Email Item"; var SelectedScenario: Enum "Email Scenario"; var SourceRef: RecordRef; DocumentNo: Code[50]; var IsHandled: Boolean)
var
    FldRef: FieldRef;
    CustomerRef: RecordRef;
    CustomerNo: Code[20];
    Customer: Record Customer;
    GeneratedReport: OutStream;
    TempBlobList: Codeunit "Temp Blob List";
    TempBlob: Codeunit "Temp Blob";
    FileNames: List of [Text];
    Name: Text;
begin
    // Check that the email contains attachments and the source is an invoice
    if Email.HasAttachments() and (SourceRef.Number() = Database::"Sales Invoice Header") then begin
        // Get the Sell-to Customer field.
        FldRef := SourceRef.Field(2);
        CustomerNo := FldRef.Value();

        // Get the customer record for the Sell-to Customer.
        Customer.Get(CustomerNo);

        // Open the customer as a RecordRef
        CustomerRef.GetTable(Customer);

        // Get the list of all attachments
        Email.GetAttachments(TempBlobList, FileNames);

        // Use the TempBlob to initialize the OutStream
        TempBlob.CreateOutStream(GeneratedReport);

        // Generate a sales report for the customer (this will generate a summary of all customers)
        Report.SaveAs(Report::"Customer - Sales List", '', ReportFormat::Pdf, GeneratedReport, CustomerRef);

        // Add the TempBlob to the list
        TempBlobList.Add(TempBlob);

        // Create a nice name for the attachment
        Name := StrSubstNo('%1 - Sales List.pdf', Customer.Name);

        // Add the name to the list so we link the name to the attachment
        FileNames.Add(Name);

        // Update the stored attachments
        Email.SetAttachments(TempBlobList, FileNames);
    end;
end;
```

{% endcode %}
