向 Azure 通信服务发送的邮件添加自定义参数

问题描述 投票:0回答:1

我们正在尝试将邮件迁移到 Azure 通信服务。 我正在尝试传递额外的数据,例如userId、organizationID 用于分析。

有什么方法可以让我通过天蓝色生态系统传递它,最终调用像 webhook 这样的东西吗?

我尝试设置一个事件网格,但它只是发送 EventGridSchema ,并且似乎没有考虑发送的附加参数。 我尝试通过 REST 而不是 SDK 发送邮件并添加“数据”json,但 Azure 只是忽略它(我认为我可以使用 data.key1 的技巧并将其传递到 webhook)。

这里的任何线索将不胜感激。我正在尝试让邮件正常工作,但同时也让分析工作发挥作用。邮件数据似乎没有反映在azure的事件中。

    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)
azure email azure-eventgrid custom-events azure-communication-services
1个回答
0
投票

无法向邮件发送JSON参数的原因是邮件正文中没有添加JSON参数。下面的示例代码发送一封电子邮件,其中包含 JSON 格式的订单详细信息。

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; }
    }

输出:

enter image description here

enter image description here

下面的代码会异步发送一封包含订单摘要的电子邮件。

  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>";





输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.