Custom parameters addition to mail sent Azure Communication Services

85 Views Asked by At

We're trying to migrate to Azure Communication Services for mail. I'm trying to pass additional data e.g. userId, organizationID for the sake of analytics.

Is there any way I can pass this through the azure ecosystem to finally call anything like a webhook?

I've tried setting up an event grid but that just sends EventGridSchema out and doesn't seem to consider the additional parameters sent. I've tried sending the mail via REST instead of the SDK and add 'data' json but Azure just ignores it (I thought i could use the trick of data.key1 and pass it along to the webhook).

Any leads here would be highly appreciated. I'm trying to get mail to work but analytics to work on the side too. The mail data doesn't seem to reflect in azure's events.

    internal static class EmailQuickstart
        {
            static async Task Main1(string[] args)
            {
                
               
                string connectionString = "myConnectionString";
                var emailClient = new EmailClient(connectionString);
    
                try
                {
                    Console.WriteLine("Sending email...");
                    var messageContent = new ExtendedEmailMessageContent(subject: "Test Email Hope this works 12")
                    {
                        PlainText = "<html><h1>Hello world via email from me 10.</h1l></html>",
                        Html = "Hello world via email from me 12"
                    }; 
                    var emailMessage = new ExtendedEmailMessage(senderAddress: "[email protected]",new EmailRecipients(new List<EmailAddress> { new("[email protected]") }), messageContent);
                    emailMessage.data.Add("orgid", "2");
                    emailMessage.data.Add("userid", "1234");
                    emailMessage.orgid = "1";
                    emailMessage.userid = "1234";
                    
                    messageContent.data.Add("orgid", "2");
                    messageContent.data.Add("userid", "1234");
                    messageContent.orgid = "1";
                    messageContent.userid = "1234";
                    
                    emailMessage.Headers.Add("orgid", "1");   
                    emailMessage.Headers.Add("userid", "1234");
                    EmailSendOperation emailSendOperation = await emailClient.SendAsync(
                        WaitUntil.Completed,
                        emailMessage);
                    EmailSendResult statusMonitor = emailSendOperation.Value;
                    
                    Console.WriteLine($"Email Sent. Status = {statusMonitor.Status}");
    
                    // Get the OperationId so that it can be used for tracking the message for troubleshooting
                    string operationId = emailSendOperation.Id;
                    Console.WriteLine($"Email operation id = {operationId}");
                }
                catch (RequestFailedException ex)
                {
                    /// OperationID is contained in the exception message and can be used for troubleshooting purposes
                    Console.WriteLine($"Email send operation failed with error code: {ex.ErrorCode}, message: {ex.Message}");
                }
    
            }
            
            public class ExtendedEmailMessageContent : EmailContent
            {
                // Additional properties you want to include
                public Dictionary<string, string> data { get; set; }
                
                public string orgid { get; set; }
                
                public string userid { get; set; }
                
                public ExtendedEmailMessageContent(string subject)
                    : base(subject)
                {
                    data = new Dictionary<string, string>();
                }
    
            }
            
            public class ExtendedEmailMessage : EmailMessage
            {
                // Additional properties you want to include
                public Dictionary<string, string> data { get; set; }
                
                public string orgid { get; set; }
                
                public string userid { get; set; }
    
                public ExtendedEmailMessage(string senderAddress, EmailRecipients recipients, EmailContent content)
                    : base(senderAddress, recipients, content)
                {
                    data = new Dictionary<string, string>();
                }
    
            }
        }

Python:


    from azure.communication.email import EmailClient
    from azure.core.credentials import AzureKeyCredential
    
    credential = AzureKeyCredential("")
    endpoint = "https://my-communication-service.unitedstates.communication.azure.com/"
    client = EmailClient(endpoint, credential)
    
    message = {
        "content": {
            "subject": "This is python SDK code based email",
            "plainText": "This is message from body... Blah Blah Blah",
            "html": "<html><h1>This is message from body... Blah Blah Blah</h1></html>"
        },
        "recipients": {
            "to": [
                {
                    "address": "[email protected]",
                    "displayName": "Karan Nanda"
                }
            ]
        },
        "data": {
          "orgid": "1",
          "userid": "1234"
        },
        "senderAddress": "[email protected]"
    }
    
    poller = EmailClient.begin_send(client, message)
    result = poller.result()
    print(result)
1

There are 1 best solutions below

2
Sampath On

The reason for being unable to send a JSON parameter to the mail is that the JSON parameters are not added to the mail body. The sample code below sends an email with the order details in JSON format.

using System;
using System.Threading.Tasks;
using Azure;
using Azure.Communication.Email;
using System.Text.Json;

namespace SendEmail
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
           
            var sender = "[email protected]";
            var recipient = "[email protected]";

            var order = new Order
            {
                OrderId = "12345",
                CustomerName = "David",
                Items = new[]
                {
                    new Item { Name = "product one", Price = "1.99" },
                    new Item { Name = "product two", Price = "2.99" },
                    new Item { Name = "product three", Price = "3.99" }
                }
            };

            var jsonContent = JsonSerializer.Serialize(order.Items);

            var subject = "Your Order";

            try
            {
  
                string connectionString = "endpoint=https://sampath8.unitedstates.communication.azure.com/;accesskey=SharedAccessKey ";

             
                EmailClient emailClient = new EmailClient(connectionString);

                Console.WriteLine("Sending email...");
           
                EmailSendOperation emailSendOperation = await emailClient.SendAsync(
                    Azure.WaitUntil.Completed,
                    sender,
                    recipient,
                    subject,
                    jsonContent);

                EmailSendResult statusMonitor = emailSendOperation.Value;

                Console.WriteLine($"Email Sent. Status = {emailSendOperation.Value.Status}");

    
                string operationId = emailSendOperation.Id;
                Console.WriteLine($"Email operation id = {operationId}");

   

            }
            catch (RequestFailedException ex)
            {
                
                Console.WriteLine($"Email send operation failed with error code: {ex.ErrorCode}, message: {ex.Message}");
            }
        }
    }

    public class Order
    {
        public string? OrderId { get; set; }
        public string? CustomerName { get; set; }
        public Item[] Items { get; set; }
    }

    public class Item
    {
        public string? Name { get; set; }
        public string? Price { get; set; }
    }

Output:

enter image description here

enter image description here

The code below sends an email containing an order summary and does so asynchronously.

  var sender = "[email protected]";
            var recipient = "[email protected]";

            var order = new Order
            {
                OrderId = "12345",
                CustomerName = "David",
                Items = new[]
                {
                    new Item { Name = "product one", Price = "1.99" },
                    new Item { Name = "product two", Price = "2.99" },
                    new Item { Name = "product three", Price = "3.99" }
                }
            };

            var htmlContent = RenderOrderHtml(order);
            var subject = "Your Order";

            try
            {
        
                string connectionString = "endpoint=https://sampath8.unitedstates.communication.azure.com/;accesskey=SharedAccessKey ";


                EmailClient emailClient = new EmailClient(connectionString);

                Console.WriteLine("Sending email...");
              
                EmailSendOperation emailSendOperation = await emailClient.SendAsync(
                    Azure.WaitUntil.Completed,
                    sender,
                    recipient,
                    subject,
                    htmlContent);

            
                EmailSendResult statusMonitor = emailSendOperation.Value;

                Console.WriteLine($"Email Sent. Status = {emailSendOperation.Value.Status}");

               
                string operationId = emailSendOperation.Id;
                Console.WriteLine($"Email operation id = {operationId}");

        

            }
            catch (RequestFailedException ex)
            {
         
                Console.WriteLine($"Email send operation failed with error code: {ex.ErrorCode}, message: {ex.Message}");
            }
        }

        static string RenderOrderHtml(Order order)
        {
            return $@"
                <html>
                <head>
                    <title>Your Order</title>
                </head>
                <body>
                    <div>
                        <h1>Order: {order.OrderId}</h1>
                        <div>
                            <p>Hi {order.CustomerName},</p>

                            <p>Here is your order:</p>

                            <table>
                                <tr>
                                    <th>Item Name</th>
                                    <th>Price</th>
                                </tr>
                                {string.Join("", order.Items.Select(item => $@"
                                    <tr>
                                        <td>{item.Name}</td>
                                        <td>{item.Price}</td>
                                    </tr>"))}
                            </table>
                        </div>
                    </div>
                </body>
                </html>";

Output:

enter image description here

Updated: The code sample below encodes the metadata into the email subject or body.

var sender = "[email protected]";
            var recipient = "[email protected]";

            var order = new Order
            {
                OrderId = "12345",
                CustomerName = "David",
                Items = new[]
                {
                    new Item { Name = "product one", Price = "1.99" },
                    new Item { Name = "product two", Price = "2.99" },
                    new Item { Name = "product three", Price = "3.99" }
                }
            };

            var jsonContent = JsonSerializer.Serialize(order);
            var subject = "Your Order";
            var metadata = jsonContent;

            try
            {
                string connectionString = "endpoint=https://sampath8.unitedstates.communication.azure.com/;accesskey=SharedAccessKey ";
                EmailClient emailClient = new EmailClient(connectionString);

                Console.WriteLine("Sending email...");

                // Add metadata to the subject
                subject += $" | Metadata: {metadata}";

                EmailSendOperation emailSendOperation = await emailClient.SendAsync(
                    Azure.WaitUntil.Completed,
                    sender,
                    recipient,
                    subject,
                    htmlContent: "<p>Your email content here</p>",
                    plainTextContent: "Your email content here");

                EmailSendResult statusMonitor = emailSendOperation.Value;

                Console.WriteLine($"Email Sent. Status = {emailSendOperation.Value.Status}");

                string operationId = emailSendOperation.Id;
                Console.WriteLine($"Email operation id = {operationId}");
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine($"Email send operation failed with error code: {ex.ErrorCode}, message: {ex.Message}");
            }
        }

Output: enter image description here