Пример #1
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            var parser       = new WebhookParser();
            var inboundEmail = parser.ParseInboundEmailWebhook(req.Body);

            log.LogInformation($"EmailForward received new email from {inboundEmail.From.Email}");

            double score = 0.0;

            if (!string.IsNullOrEmpty(inboundEmail.SpamScore))
            {
                score = double.Parse(inboundEmail.SpamScore);
                if (score >= 5.0)
                {
                    log.LogInformation($"Discarding email due to spam score of {score}");
                    return(new OkObjectResult("EmailForward discarded email due to spam!"));
                }
            }

            string response = await ForwardEmail(inboundEmail, score, log);

            if (string.IsNullOrEmpty(response))
            {
                log.LogError($"EmailForward FAILED");
                return(new OkObjectResult("EmailForward failed to send email!"));
            }

            log.LogInformation($"EmailForward successfully forwarded email {response}");
            return(new OkObjectResult($"EmailForward successfully forwarded email {response}"));
        }
Пример #2
0
        public async Task <IActionResult> Email()
        {
            var          parser       = new WebhookParser();
            InboundEmail inboundEmail = parser.ParseInboundEmailWebhook(Request.Body);
            await _messageSink.ProcessMessageAsync(CreateMessage(inboundEmail));

            return(Ok());
        }
Пример #3
0
        public void RawPayloadWithAttachments()
        {
            var parser = new WebhookParser();

            using (Stream stream = new MemoryStream())
            {
                using (var fileStream = File.OpenRead("InboudEmailTestData/raw_data.txt"))
                {
                    fileStream.CopyTo(stream);
                }
                stream.Position = 0;

                InboundEmail inboundEmail = parser.ParseInboundEmailWebhook(stream);

                inboundEmail.ShouldNotBeNull();

                inboundEmail.Dkim.ShouldBe("{@sendgrid.com : pass}");

                var rawEmailTestData = File.ReadAllText("InboudEmailTestData/raw_email.txt");
                inboundEmail.RawEmail.Trim().ShouldBe(rawEmailTestData);

                inboundEmail.To[0].Email.ShouldBe("*****@*****.**");
                inboundEmail.To[0].Name.ShouldBe(string.Empty);

                inboundEmail.Cc.Length.ShouldBe(0);

                inboundEmail.From.Email.ShouldBe("*****@*****.**");
                inboundEmail.From.Name.ShouldBe("Example User");

                inboundEmail.SenderIp.ShouldBe("0.0.0.0");

                inboundEmail.SpamReport.ShouldBeNull();

                inboundEmail.Envelope.From.ShouldBe("*****@*****.**");
                inboundEmail.Envelope.To.Length.ShouldBe(1);
                inboundEmail.Envelope.To.ShouldContain("*****@*****.**");

                inboundEmail.Subject.ShouldBe("Raw Payload");

                inboundEmail.SpamScore.ShouldBeNull();

                inboundEmail.Charsets.Except(new[]
                {
                    new KeyValuePair <string, Encoding>("to", Encoding.UTF8),
                    new KeyValuePair <string, Encoding>("subject", Encoding.UTF8),
                    new KeyValuePair <string, Encoding>("from", Encoding.UTF8)
                }).Count().ShouldBe(0);

                inboundEmail.Spf.ShouldBe("pass");
            }
        }
Пример #4
0
        public void InboundEmail()
        {
            // Arrange
            using (var stream = new MemoryStream())
            {
                using (var writer = new StreamWriter(stream))
                {
                    writer.Write(INBOUND_EMAIL_WEBHOOK);
                    writer.Flush();
                    stream.Position = 0;

                    // Act
                    var parser       = new WebhookParser();
                    var inboundEmail = parser.ParseInboundEmailWebhook(stream);

                    // Assert
                    inboundEmail.Attachments.ShouldNotBeNull();
                    inboundEmail.Attachments.Length.ShouldBe(0);
                    inboundEmail.Cc.ShouldNotBeNull();
                    inboundEmail.Cc.Length.ShouldBe(0);
                    inboundEmail.Charsets.ShouldNotBeNull();
                    inboundEmail.Charsets.Length.ShouldBe(5);
                    inboundEmail.Dkim.ShouldBe("{@hotmail.com : pass}");
                    inboundEmail.From.ShouldNotBeNull();
                    inboundEmail.From.Email.ShouldBe("*****@*****.**");
                    inboundEmail.From.Name.ShouldBe("Bob Smith");
                    inboundEmail.Headers.ShouldNotBeNull();
                    inboundEmail.Headers.Length.ShouldBe(40);
                    inboundEmail.Html.ShouldStartWith("<html", Case.Insensitive);
                    inboundEmail.SenderIp.ShouldBe("10.43.24.23");
                    inboundEmail.SpamReport.ShouldBeNull();
                    inboundEmail.SpamScore.ShouldBeNull();
                    inboundEmail.Spf.ShouldBe("softfail");
                    inboundEmail.Subject.ShouldBe("Test #1");
                    inboundEmail.Text.ShouldBe("Test #1\r\n");
                    inboundEmail.To.ShouldNotBeNull();
                    inboundEmail.To.Length.ShouldBe(1);
                    inboundEmail.To[0].Email.ShouldBe("*****@*****.**");
                    inboundEmail.To[0].Name.ShouldBe("Test Recipient");
                }
            }
        }
Пример #5
0
        public void InboundEmail_with_unusual_encoding()
        {
            // Arrange
            var parser = new WebhookParser();

            using (var stream = GetStream(INBOUND_EMAIL_UNUSUAL_ENCODING_WEBHOOK))
            {
                // Act
                var inboundEmail = parser.ParseInboundEmailWebhook(stream);

                // Assert
                inboundEmail.Charsets.ShouldNotBeNull();
                inboundEmail.Charsets.Except(new[]
                {
                    new KeyValuePair <string, Encoding>("to", Encoding.UTF8),
                    new KeyValuePair <string, Encoding>("subject", Encoding.UTF8),
                    new KeyValuePair <string, Encoding>("from", Encoding.UTF8),
                    new KeyValuePair <string, Encoding>("html", Encoding.ASCII),
                    new KeyValuePair <string, Encoding>("text", Encoding.UTF8)                          // The original encoding is iso-8859-10 but we fallback on UTF-8
                }).Count().ShouldBe(0);
                inboundEmail.Text.ShouldBe("Hello SendGrid!\r\n");
            }
        }
Пример #6
0
        public Task <InboundEmail> ParseInboundEmailWebhook(Stream requestBody)
        {
            var inboundEmail = _parser.ParseInboundEmailWebhook(requestBody);

            return(Task.FromResult(inboundEmail));
        }
Пример #7
0
        public async Task <APIGatewayHttpApiV2ProxyResponse> InboundParse(APIGatewayHttpApiV2ProxyRequest request, ILambdaContext context)
        {
            APIGatewayHttpApiV2ProxyResponse response;

            var getParameterResponse = await _ssmClient.GetParameterAsync(new GetParameterRequest
            {
                Name           = AuthenticationKeyParameterName,
                WithDecryption = true
            });

            var authenticationKey = getParameterResponse?.Parameter?.Value;

            string authenticationKeyPresented = null;

            request.QueryStringParameters?.TryGetValue(AuthenticationQueryParameterKey, out authenticationKeyPresented);

            if (string.IsNullOrEmpty(authenticationKeyPresented) || string.IsNullOrEmpty(authenticationKey) ||
                authenticationKeyPresented != authenticationKey)
            {
                context.Logger.LogLine($"Failed to authenticate.");

                return(new APIGatewayHttpApiV2ProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.Unauthorized
                });
            }

            try
            {
                context.Logger.LogLine("Request Headers:");
                foreach (var header in request.Headers)
                {
                    context.Logger.LogLine($"{header.Key}: {header.Value}");
                }
                context.Logger.LogLine($"Request IsBase64Encoded:\n{request.IsBase64Encoded}");
                context.Logger.LogLine($"Request Body:\n{request.Body}");

                var requestBody = new MemoryStream(Convert.FromBase64String(request.Body));

                var parser       = new WebhookParser();
                var inboundEmail = parser.ParseInboundEmailWebhook(requestBody);
                context.Logger.LogLine($"InboundEmail Subject:\n{inboundEmail.Subject}");
                context.Logger.LogLine($"InboundEmail To:\n{inboundEmail.To[0].Email}");
                context.Logger.LogLine($"InboundEmail From:\n{inboundEmail.From.Email}");
                context.Logger.LogLine($"InboundEmail DKIM:\n{inboundEmail.Dkim}");
                context.Logger.LogLine($"InboundEmail SPF:\n{inboundEmail.Spf}");

                context.Logger.LogLine($"InboundEmail Envelope.From:\n{inboundEmail.Envelope.From}");

                response = new APIGatewayHttpApiV2ProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.OK,
                    Body       = "Success",
                    Headers    = new Dictionary <string, string> {
                        { "Content-Type", "text/plain" }
                    }
                };
            }
            catch (Exception ex)
            {
                var exception = ex.ToString();
                context.Logger.LogLine($"Exception occurred:\n{exception}");

                response = new APIGatewayHttpApiV2ProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.OK,
                    Body       = ex.Message,
                    Headers    = new Dictionary <string, string> {
                        { "Content-Type", "text/plain" }
                    }
                };
            }

            return(response);
        }