.netazureazure-eventgridazure-communication-services

Azure Communication EventGrid retrieve headers


I am sending an email using the Azure Communication email client, as this.

        var emailMessage = new EmailMessage(
            senderAddress: "DoNotReply@myemail.com",
            content: new EmailContent(subject)
            {
                Html = "Hello World",
            },
            recipients: new EmailRecipients()));

        emailMessage.Headers.Add("x-yot-custom-id", "123abc");

I am then using the AzureEvent grid to get status updates on the message with code like this

public class EmailEventGridHook
{
    private readonly ILogger<EmailEventGridHook> _logger;

    public EmailEventGridHook(ILogger<EmailEventGridHook> logger)
    {
        _logger = logger;
    }

    [Function("EmailEventGridHook")]
    public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequest req)
    {
        _logger.LogInformation("EmailEventGridHook function processed a request.");
        string response = string.Empty;
        BinaryData events = await BinaryData.FromStreamAsync(req.Body);
        _logger.LogInformation($"Received events: {events}");

        EventGridEvent[] eventGridEvents = EventGridEvent.ParseMany(events);

        foreach (EventGridEvent eventGridEvent in eventGridEvents)
        {
            // Handle system events
            if (eventGridEvent.TryGetSystemEventData(out object eventData))
            {
                
                if (eventData is AcsEmailDeliveryReportReceivedEventData statusEvent)
                {
                    await _azureEmailClient.UpdateStatus(statusEvent.MessageId, DateTime.UtcNow, statusEvent.Recipient, statusEvent.Status?.ToString(), statusEvent.DeliveryStatusDetails.StatusMessage);
                }
            }
        }
        return new OkObjectResult(response);
    }
}

Is there any way in the event grid to access the x-yot-custom-id header as that is used to link the email back to a record in my system?

I thought I might be able to retrieve and email in the system to then get the header, but can't see a way to retrieve the message.


Solution

  • You can access custom headers like x-yot-custom-id in Event Grid by using Delivery Properties to include the header in the event data when configuring the subscription.

    Azure Communication Services doesn’t automatically propagate custom headers (emailMessage.Headers) into Event Grid events.

    You can configure delivery properties in Event Grid event subscriptions to include them. Refer this MDDOC for Custom headers for Azure Email Communication Service.

    enter image description here Update the function that processes Event Grid events to extract the x-yot-custom-id header.

      foreach (EventGridEvent eventGridEvent in eventGridEvents)
      {
          if (eventGridEvent.TryGetSystemEventData(out object eventData))
          {
              if (eventData is AcsEmailDeliveryReportReceivedEventData statusEvent)
              {
                  string customId = eventGridEvent.Subject; // Check if Subject carries your ID
                  if (eventGridEvent.Data is JsonElement dataElement && 
                      dataElement.TryGetProperty("x-yot-custom-id", out JsonElement customIdElement))
                  {
                      customId = customIdElement.GetString();
                  }
      
                  await _azureEmailClient.UpdateStatus(
                      statusEvent.MessageId, 
                      DateTime.UtcNow, 
                      statusEvent.Recipient, 
                      statusEvent.Status?.ToString(), 
                      statusEvent.DeliveryStatusDetails.StatusMessage, 
                      customId);
              }
          }
      }
    

    enter image description here