简体   繁体   English

在ASP.NET MVC(C#)中通过Amazon SNS配置Amazon SES反馈通知

[英]Configuring Amazon SES Feedback Notifications via Amazon SNS in ASP.NET MVC (C#)

Good day! 美好的一天! I'm just started with Amazon SES. 我刚开始使用Amazon SES。 I want use this in my asp.net mvc (C#) website. 我想在我的asp.net mvc(C#)网站上使用它。

I download and install AWS Toolkit for Visual Studio, create AWS simple console application. 我下载并安装适用于Visual Studio的AWS Toolkit,创建AWS简单控制台应用程序。 So, I have sample code that can send email, using AmazonSimpleEmailService client. 所以,我有使用AmazonSimpleEmailService客户端发送电子邮件的示例代码。

PART 1: 第1部分:

using (AmazonSimpleEmailService client = AWSClientFactory.CreateAmazonSimpleEmailServiceClient(RegionEndpoint.USEast1))
{
     var sendRequest = new SendEmailRequest
     {
     Source = senderAddress,
     Destination = new Destination { ToAddresses = new List<string> { receiverAddress } },
     Message = new Message
     {
        Subject = new Content("Sample Mail using SES"),
        Body = new Body { Text = new Content("Sample message content.") }
     }
     };

     Console.WriteLine("Sending email using AWS SES...");
     SendEmailResponse response = client.SendEmail(sendRequest);
     Console.WriteLine("The email was sent successfully.");
 }

Further, I must configuring Amazon SES Feedback Notifications via Amazon SNS. 此外,我必须通过Amazon SNS配置Amazon SES反馈通知。 I find nice topic with sample code: 我用示例代码找到了很好的主题:

PART 3: http://sesblog.amazon.com/post/TxJE1JNZ6T9JXK/Handling-Bounces-and-Complaints 第3部分: http//sesblog.amazon.com/post/TxJE1JNZ6T9JXK/Handling-Bounces-and-Complaints

So, I need make PART 2 where I'll get ReceiveMessageResponse response and send it into PART 3. 因此,我需要制作第2部分,我将获得ReceiveMessageResponse响应并将其发送到第3部分。

I need implement in C# this steps: Set up the following AWS components to handle bounce notifications: 我需要在C#中实现这一步骤:设置以下AWS组件来处理退回通知:

1. Create an Amazon SQS queue named ses-bounces-queue.
2. Create an Amazon SNS topic named ses-bounces-topic.
3. Configure the Amazon SNS topic to publish to the SQS queue.
4. Configure Amazon SES to publish bounce notifications using ses-bounces-topic to ses-bounces-queue.

I try write it: 我试着写下来:

// 1. Create an Amazon SQS queue named ses-bounces-queue.
 AmazonSQS sqs = AWSClientFactory.CreateAmazonSQSClient(RegionEndpoint.USWest2);
                    CreateQueueRequest sqsRequest = new CreateQueueRequest();
                    sqsRequest.QueueName = "ses-bounces-queue";
                    CreateQueueResponse createQueueResponse = sqs.CreateQueue(sqsRequest);
                    String myQueueUrl;
                    myQueueUrl = createQueueResponse.CreateQueueResult.QueueUrl;
// 2. Create an Amazon SNS topic named ses-bounces-topic
AmazonSimpleNotificationService sns = new AmazonSimpleNotificationServiceClient(RegionEndpoint.USWest2);
                    string topicArn = sns.CreateTopic(new CreateTopicRequest
                    {
                        Name = "ses-bounces-topic"
                    }).CreateTopicResult.TopicArn;
// 3. Configure the Amazon SNS topic to publish to the SQS queue
                    sns.Subscribe(new SubscribeRequest
                    {
                        TopicArn = topicArn,
                        Protocol = "https",
                        Endpoint = "ses-bounces-queue"
                    });
// 4. Configure Amazon SES to publish bounce notifications using ses-bounces-topic to ses-bounces-queue
                    clientSES.SetIdentityNotificationTopic(XObject);

I'm on the right track? 我走在正确的轨道上?

How I can implement 4 part? 我如何实施4部分? How receive XObject? 如何接收XObject?

Thanks! 谢谢!

You are on the right track - for the missing part 4 you need to implement receiving of a message from the Amazon SQS message queue you created in step 1. See my answer to Example of .net application using Amazon SQS for where to find a respective example - it boils down to the following code: 您正走在正确的轨道上 - 对于缺失的第4部分,您需要实现从步骤1中创建的Amazon SQS消息队列接收消息。请参阅我对使用Amazon SQS的.net应用程序示例的答案,了解各自的位置示例 - 它归结为以下代码:

// receive a message
ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest();
receiveMessageRequest.QueueUrl = myQueueUrl;
ReceiveMessageResponse receiveMessageResponse = sqs.
   ReceiveMessage(receiveMessageRequest);
if (receiveMessageResponse.IsSetReceiveMessageResult())
{
    Console.WriteLine("Printing received message.\n");
    ReceiveMessageResult receiveMessageResult = receiveMessageResponse.
        ReceiveMessageResult;
    foreach (Message message in receiveMessageResult.Message)
    {
        // process the message (see below)
    }
}

Within the loop you need to call either ProcessQueuedBounce() or ProcessQueuedComplaint() as illustrated in Handling Bounces and Complaints . 在循环中,您需要调用ProcessQueuedBounce()ProcessQueuedComplaint()处理退回和投诉中所示

I've recently had to tackle this problem and I couldn't find a good code example on how to handle the SNS bounce notification (as well as topic subscription request) from a .Net website. 我最近不得不解决这个问题,我找不到一个关于如何从.Net网站处理SNS退回通知(以及主题订阅请求)的好代码示例。 Here's the Web API method I came up with to handle SNS bounce notifications from Amazon SES. 这是我提出的处理来自Amazon SES的SNS退回通知的Web API方法。

The code is in VB but any online VB to C# converter should be able to easily get it converted for you. 代码在VB中,但任何在线VB到C#转换器都应该能够轻松地为您转换。

Imports System.Web.Http
Imports Amazon.SimpleNotificationService

Namespace Controllers
    Public Class AmazonController
        Inherits ApiController

        <HttpPost>
        <Route("amazon/bounce-handler")>
        Public Function HandleBounce() As IHttpActionResult

            Try
                Dim msg = Util.Message.ParseMessage(Request.Content.ReadAsStringAsync().Result)

                If Not msg.IsMessageSignatureValid Then
                    Return BadRequest("Invalid Signature!")
                End If

                If msg.IsSubscriptionType Then
                    msg.SubscribeToTopic()
                    Return Ok("Subscribed!")
                End If

                If msg.IsNotificationType Then

                    Dim bmsg = Newtonsoft.Json.JsonConvert.DeserializeObject(Of Message)(msg.MessageText)

                    If bmsg.notificationType = "Bounce" Then

                        Dim emails = (From e In bmsg.bounce.bouncedRecipients
                                      Select e.emailAddress).Distinct()

                        If bmsg.bounce.bounceType = "Permanent" Then
                            For Each e In emails
                                'this email address is permanantly bounced. don't ever send any mails to this address. remove from list.
                            Next
                        Else
                            For Each e In emails
                                'this email address is temporarily bounced. don't send any more emails to this for a while. mark in db as temp bounce.
                            Next
                        End If

                    End If

                End If

            Catch ex As Exception
                'log or notify of this error to admin for further investigation
            End Try

            Return Ok("done...")

        End Function

        Private Class BouncedRecipient
            Public Property emailAddress As String
            Public Property status As String
            Public Property diagnosticCode As String
            Public Property action As String
        End Class

        Private Class Bounce
            Public Property bounceSubType As String
            Public Property bounceType As String
            Public Property reportingMTA As String
            Public Property bouncedRecipients As BouncedRecipient()
            Public Property timestamp As DateTime
            Public Property feedbackId As String
        End Class

        Private Class Mail
            Public Property timestamp As DateTime
            Public Property source As String
            Public Property sendingAccountId As String
            Public Property messageId As String
            Public Property destination As String()
            Public Property sourceArn As String
        End Class

        Private Class Message
            Public Property notificationType As String
            Public Property bounce As Bounce
            Public Property mail As Mail
        End Class

    End Class

End Namespace

I have the same problem today. 我今天也有同样的问题。 I solved the problem by configuring a WebHook (https) in the SNS configuration. 我通过在SNS配置中配置WebHook(https)解决了这个问题。 On the webserver i process now the events. 在网络服务器上,我现在处理事件。 I have create a nuget package with the logic. 我用逻辑创建了一个nuget包。

My Code - Nager.AmazonSesNotification 我的代码 - Nager.AmazonSesNotification

[Route("SesNotification")]
[HttpPost]
public async Task<IActionResult> SesNotificationAsync()
{
    var body = string.Empty;
    using (var reader = new StreamReader(Request.Body))
    {
        body = await reader.ReadToEndAsync();
    }

    var notificationProcessor = new NotificationProcessor();
    var result = await notificationProcessor.ProcessNotificationAsync(body);

    //Your processing logic...

    return StatusCode(StatusCodes.Status200OK);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM