Пример #1
0
        static public async Task <bool> SendEmail(string to, string replyTo, string subject, string body)
        {
            Message msg = new Message(new Content(subject), new Body()
            {
                Html = new Content(body)
            });
            SendEmailRequest req = new SendEmailRequest("*****@*****.**", new Destination(new List <string> {
                to
            }), msg)
            {
                ReturnPath = "*****@*****.**"
            };

            if (!String.IsNullOrWhiteSpace(replyTo))
            {
                req.ReplyToAddresses.Add(replyTo);
            }
            using (AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(new BasicAWSCredentials(Settings.SESAccessKey, Settings.SESSecret), RegionEndpoint.USWest2))
            {
                try
                {
                    var resp = await client.SendEmailAsync(req);

                    return(true);
                }
                catch
                {
                    return(false);
                }
            }
        }
        public void GetEmailTemplate(string templateName)
        {
            using (AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(_regionEndpoint))
            {
                try
                {
                    GetTemplateResponse getTemplateResponse = client.GetTemplateAsync(new GetTemplateRequest {
                        TemplateName = templateName
                    }).Result;
                    _logger.LogInformation($"GetTemplateResponse.HttpStatusCode = {getTemplateResponse.HttpStatusCode}");
                    _logger.LogInformation($"GetTemplateResponse.Template.TemplateName = {getTemplateResponse.Template.TemplateName}");
                    _logger.LogInformation($"GetTemplateResponse.Template.Subject = {getTemplateResponse.Template.SubjectPart}");
                    _logger.LogInformation($"GetTemplateResponse.Template.TextPart = {getTemplateResponse.Template.TextPart}");
                }
                catch (Exception e)
                {
                    _logger.LogError($"Failure while fetching template {templateName}, Error Message = " + e.Message);
                    _logger.LogError($"Failure while fetching template {templateName}, e.InnerException.GetType() = {e.InnerException.GetType()}");

                    if (e.InnerException.GetType() == typeof(TemplateDoesNotExistException))
                    {
                        _logger.LogError($"Failure while fetching template {templateName}, Template doesn't exist, Error Message = " + e.Message);
                        throw e.InnerException;
                    }

                    throw e;
                }
            }
        }
        public AmazonSesMailDeliveryService(
            GlobalSettings globalSettings,
            IWebHostEnvironment hostingEnvironment,
            ILogger <AmazonSesMailDeliveryService> logger)
        {
            if (string.IsNullOrWhiteSpace(globalSettings.Amazon?.AccessKeyId))
            {
                throw new ArgumentNullException(nameof(globalSettings.Amazon.AccessKeyId));
            }
            if (string.IsNullOrWhiteSpace(globalSettings.Amazon?.AccessKeySecret))
            {
                throw new ArgumentNullException(nameof(globalSettings.Amazon.AccessKeySecret));
            }
            if (string.IsNullOrWhiteSpace(globalSettings.Amazon?.Region))
            {
                throw new ArgumentNullException(nameof(globalSettings.Amazon.Region));
            }

            _globalSettings     = globalSettings;
            _hostingEnvironment = hostingEnvironment;
            _logger             = logger;
            _client             = new AmazonSimpleEmailServiceClient(globalSettings.Amazon.AccessKeyId,
                                                                     globalSettings.Amazon.AccessKeySecret, RegionEndpoint.GetBySystemName(globalSettings.Amazon.Region));
            _source    = $"\"{globalSettings.SiteName}\" <{globalSettings.Mail.ReplyToEmail}>";
            _senderTag = $"Server_{globalSettings.ProjectName}";
            if (!string.IsNullOrWhiteSpace(_globalSettings.Mail.AmazonConfigSetName))
            {
                _configSetName = _globalSettings.Mail.AmazonConfigSetName;
            }
        }
Пример #4
0
        public async Task <EmailResult> SendEmail(EmailOptions options)
        {
            // Replace USWest2 with the AWS Region you're using for Amazon SES.
            // Acceptable values are EUWest1, USEast1, and USWest2.
            using (var client = new AmazonSimpleEmailServiceClient(Settings.Default.AccessKey.FromBase64(), Settings.Default.SecretKey.FromBase64(), RegionEndpoint.USEast1))
            {
                var sendRequest = new SendRawEmailRequest {
                    RawMessage = new RawMessage(GetMessageStream(options))
                };
                try
                {
                    Console.WriteLine("Sending email using Amazon SES...");
                    var response = await client.SendRawEmailAsync(sendRequest);

                    return(new EmailResult()
                    {
                        EmailId = response.MessageId,
                        StatusCode = response.HttpStatusCode.ToString()
                    });
                }
                catch (Exception ex)
                {
                    Console.WriteLine("The email was not sent. " + ex.ToString());
                    return(new EmailResult()
                    {
                        Error = ex.ToString(),
                        StatusCode = "500"
                    });
                }
            }
        }
Пример #5
0
 protected void SendMail(string url)
 {
     using (var sesClient = new AmazonSimpleEmailServiceClient(bucketRegion))
     {
         var sendRequest = new SendEmailRequest
         {
             Source      = "*****@*****.**",
             Destination = new Destination {
                 ToAddresses = new List <string> {
                     UserEmail
                 }
             },
             Message = new Message
             {
                 Subject = new Amazon.SimpleEmail.Model.Content("Here's your file!"),
                 Body    = new Body {
                     Text = new Amazon.SimpleEmail.Model.Content("Your download link!" + url)
                 }
             }
         };
         try
         {
             var response = sesClient.SendEmailAsync(sendRequest);
             Console.WriteLine("email sent to: " + UserEmail);
         }
         catch (Exception ex)
         {
             Console.WriteLine("error message: " + ex.Message);
         }
     }
 }
Пример #6
0
        public void SendEmail()
        {
            if (_weatherEvaluators.Count == 0)
            {
                return;
            }

            string mainEmailMessage = this.buildBody();
            string htmlBody         = @"<html>
                    <head></head>
                    <body>
                      " + mainEmailMessage + @"
                    </body>
                    </html>";



            using (var client = new AmazonSimpleEmailServiceClient(RegionEndpoint.USEast1))
            {
                var sendRequest = new SendEmailRequest
                {
                    Source      = senderAddress,
                    Destination = new Destination
                    {
                        ToAddresses = _receiverAddresses
                    },
                    Message = new Message
                    {
                        Subject = new Content(subject),
                        Body    = new Body
                        {
                            Html = new Content
                            {
                                Charset = "UTF-8",
                                Data    = htmlBody
                            },
                            Text = new Content
                            {
                                Charset = "UTF-8",
                                Data    = textBody
                            }
                        }
                    },
                    // If you are not using a configuration set, comment
                    // or remove the following line
                    //ConfigurationSetName = configSet
                };
                try
                {
                    Console.WriteLine("Sending email using Amazon SES...");
                    var response = client.SendEmailAsync(sendRequest);
                    Console.WriteLine("The email was sent successfully.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("The email was not sent.");
                    Console.WriteLine("Error message: " + ex.Message);
                }
            }
        }
Пример #7
0
        public async Task <MessageDispatchResult> SendAsync(IMessage message)
        {
            var mailMessage = EmailMessage.CreateFromMessage(message);

            var credentials = this.GetCredentials();

            var client = new AmazonSimpleEmailServiceClient(credentials);

            var request = new SendRawEmailRequest {
                RawMessage = new RawMessage {
                    Data = RawMailHelper.ConvertMailMessageToMemoryStream(mailMessage)
                }
            };

            var response = await client.SendRawEmailAsync(request);

            if (response.HttpStatusCode == HttpStatusCode.OK && !string.IsNullOrEmpty(response.MessageId))
            {
                return(new MessageDispatchResult {
                    Succeeded = true, MessageId = response.MessageId
                });
            }

            return(new MessageDispatchResult
            {
                Succeeded = false,
                MessageId = response.MessageId,
                Errors = $"{response.HttpStatusCode}: {StringifyMetaData(response.ResponseMetadata)}"
            });
        }
Пример #8
0
        public async Task <bool> SendEmail(List <string> to, string subject, string message, string link, string linkText)
        {
            var awsAccessKeyId     = _config["AppSettings:AwsAccessKeyId"];
            var awsSecretAccessKey = _config["AppSettings:AwsSecretAccessKey"];

            var body = MailBody
                       .CreateBody()
                       .Paragraph("Hello,")
                       .Paragraph(message)
                       .Button("https://rankedtyping.com" + link, linkText)
                       .Paragraph("- RankedTyping Team")
                       .ToString();

            using (var ses = new AmazonSimpleEmailServiceClient(awsAccessKeyId, awsSecretAccessKey, RegionEndpoint.USEast1))
            {
                var sendResult = await ses.SendEmailAsync(new SendEmailRequest
                {
                    Source      = "*****@*****.**",
                    Destination = new Destination(to),
                    Message     = new Message
                    {
                        Subject = new Content(subject),
                        Body    = new Body
                        {
                            Html = new Content(body)
                        }
                    }
                });

                return(sendResult.HttpStatusCode == HttpStatusCode.OK);
            }
        }
        public async Task SendAsync(MailMessageDTO message)
        {
            if (message.Attachments.Any())
            {
                throw new NotSupportedException("Amazon SES API doesn't support e-mail attachments!");
            }

            using (var client = new AmazonSimpleEmailServiceClient(awsAccessKeyId, awsSecretAccessKey))
            {
                var sendRequest = new SendEmailRequest
                {
                    Source      = message.From.Address,
                    Destination = new Destination
                    {
                        ToAddresses  = message.To.Select(t => t.Address).ToList(),
                        CcAddresses  = message.Cc.Select(t => t.Address).ToList(),
                        BccAddresses = message.Bcc.Select(t => t.Address).ToList()
                    },
                    ReplyToAddresses = message.ReplyTo.Select(t => t.Address).ToList(),
                    Message          = new Message
                    {
                        Subject = new Content(message.Subject),
                        Body    = new Body
                        {
                            Text = new Content(message.BodyText),
                            Html = new Content(message.BodyHtml)
                        }
                    }
                };
                await client.SendEmailAsync(sendRequest);
            }
        }
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonSimpleEmailServiceConfig config = new AmazonSimpleEmailServiceConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(creds, config);

            ListCustomVerificationEmailTemplatesResponse resp = new ListCustomVerificationEmailTemplatesResponse();

            do
            {
                ListCustomVerificationEmailTemplatesRequest req = new ListCustomVerificationEmailTemplatesRequest
                {
                    NextToken = resp.NextToken
                    ,
                    MaxResults = maxItems
                };

                resp = client.ListCustomVerificationEmailTemplates(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.CustomVerificationEmailTemplates)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextToken));
        }
Пример #11
0
        public async Task AmazonEmailSendAsync(string userToaddress, string subject, string body)
        {
            try
            {
                var    builder = new BodyBuilder();
                string EmailConfirmationCode = RandomString(10, false);
                builder.HtmlBody = body;
                var oMessage = new MimeMessage();

                oMessage.From.Add(new MailboxAddress("Autumn", ""));
                oMessage.To.Add(new MailboxAddress(userToaddress));
                oMessage.Subject = subject;
                oMessage.Body    = builder.ToMessageBody();

                var stream = new MemoryStream();
                oMessage.WriteTo(stream);
                var request = new SendRawEmailRequest
                {
                    RawMessage = new RawMessage {
                        Data = stream
                    },
                    Source = ""
                };

                using (var client = new AmazonSimpleEmailServiceClient())
                {
                    var response = await client.SendRawEmailAsync(request);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Пример #12
0
        static void Main(string[] args)
        {
            Console.WriteLine("Sending Email...");
            // new Body(new Content("This is an email message sent from SES."))
            using (var client = new AmazonSimpleEmailServiceClient(region: Amazon.RegionEndpoint.USEast1))
            {
                var sendRequest = new SendEmailRequest
                {
                    Source      = "*****@*****.**",
                    Destination = new Destination {
                        ToAddresses = { "*****@*****.**" }
                    },
                    Message = new Message
                    {
                        Subject = new Content("Hello from the Amazon Simple Email Service!"),
                        Body    = new Body
                        {
                            Html = new Content("<html><body><h2>Hello from Amazon SES</h2><ul><li>I'm a list item</li><li>So am I!</li></body></html>")
                        }
                    }
                };

                try
                {
                    var response = client.SendEmailAsync(sendRequest).Result;
                    Console.WriteLine("Email sent! Message ID = {0}", response.MessageId);
                } catch (Exception ex)
                {
                    Console.WriteLine("Send failed with exception: {0}", ex.Message);
                }
            }
            Console.Write("Press any key to continue...");
            Console.ReadKey();
        }
Пример #13
0
        //verifica o status do e-mail na aws
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                using (var client = new AmazonSimpleEmailServiceClient(awsAccessKeyId, awsSecretAccessKey, RegionEndpoint.SAEast1))
                {
                    var response = client.GetIdentityVerificationAttributes(new GetIdentityVerificationAttributesRequest
                    {
                        Identities = new List <string> {
                            textBox1.Text
                        }
                    });

                    Dictionary <string, IdentityVerificationAttributes> verificationAttributes = response.VerificationAttributes;

                    foreach (var i in verificationAttributes)
                    {
                        label1.Text    = "";
                        label1.Text    = "Status do E-mail: " + i.Value.VerificationStatus;
                        label1.Visible = true;
                    }
                }
            }
            catch (Exception err)
            {
                MessageBox.Show("Ocorreu um problema, verifique!: " + err.Message);
            }
        }
Пример #14
0
        static async Task Main(string[] args)
        {
            using (var client = new AmazonSimpleEmailServiceClient(awsAccessKey, awsSecretKey, RegionEndpoint.USWest2))
            {
                var watch = new System.Diagnostics.Stopwatch();

                watch.Start();
                int counter = 0;

                int sent = 10;
                Parallel.For(0, sent, new ParallelOptions {
                    MaxDegreeOfParallelism = 4
                }, count =>
                {
                    int progress = Interlocked.Increment(ref counter);
                    var subject  = "my subject " + counter.ToString();
                    SendEmailRequest sentEmailRequest = SendEmail(subject).Result;
                    Console.WriteLine("Sending email using Amazon SES...");
                    var response = client.SendEmailAsync(sentEmailRequest);
                    Console.WriteLine("The email was sent successfully.");
                });
                watch.Stop();
                TimeSpan ts = watch.Elapsed;

                Console.WriteLine($"It took {ts.Seconds} seconds");

                Console.ReadKey();
            }
        }
Пример #15
0
        public static async Task <bool> SendEmail(string sender, string recipient, string subject, string body, string accedId, string accessKey)
        {
            try
            {
                using (AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(accedId, accessKey, RegionEndpoint.EUWest2))
                {
                    SendEmailRequest req = new SendEmailRequest();

                    req.Source      = sender;
                    req.Destination = new Destination(new List <string>()
                    {
                        recipient
                    });
                    req.Message = new Message();
                    Content html = new Content(body);
                    req.Message.Body      = new Body();
                    req.Message.Body.Html = html;
                    req.Message.Body.Text = new Content("Please enable html");
                    req.Message.Subject   = new Content(subject);

                    SendEmailResponse res = await client.SendEmailAsync(req).ConfigureAwait(false);

                    return(true);
                }
            } catch
            {
                return(false);
            }
        }
Пример #16
0
        public async Task <Object> Postman(string source, string destination, List <string> ccdestination, List <string> bccdestination, string subject, string body)
        {
            Console.WriteLine("Sending Email...");
            using (var client = new AmazonSimpleEmailServiceClient(Amazon.RegionEndpoint.USEast1))
            {
                var sendRequest = new SendEmailRequest
                {
                    Source      = source.ToString(),
                    Destination = new Destination {
                        ToAddresses = { destination }, CcAddresses = ccdestination, BccAddresses = bccdestination
                    },
                    Message = new Message
                    {
                        Subject = new Content(subject.ToString()),
                        Body    = new Body
                        {
                            Html = new Content(body.ToString())
                        }
                    }
                };

                try
                {
                    var response = client.SendEmailAsync(sendRequest).Result;
                    Console.WriteLine("Email sent! Message ID = {0}", response.MessageId);
                    return(new { response = response.MessageId });
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Send failed with exception: {0}", ex.Message);
                    return(new { error = ex.Message });
                }
            }
        }
Пример #17
0
        public void SendEmail(string fromAddress, string toAddress, string _subject, string _body)
        {
            Destination destination = new Destination();

            destination.ToAddresses = (new List <string>()
            {
                toAddress
            });
            Content subject  = new Content(_subject);
            Content textBody = new Content(_body);
            Body    body     = new Body(textBody);

            Message message = new Message(subject, body);

            SendEmailRequest request = new SendEmailRequest(fromAddress, destination, message);

            Amazon.RegionEndpoint REGION = Amazon.RegionEndpoint.USEast1;

            // Instantiate an Amazon SES client, which will make the service call.
            AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(REGION);

            // Send the email.
            try
            {
                //("Attempting to send an email through Amazon SES by using the AWS SDK for .NET...");
                client.SendEmail(request);
                //("Email sent!");
            }
            catch (Exception ex)
            {
                //("Error message: " + ex.Message);
            }
        }
Пример #18
0
 static void Main(string[] args)
 {
     //Remember to enter your (AWSAccessKeyID, AWSSecretAccessKey) if not using and IAM User with credentials assigned to your instance and your RegionEndpoint
     using (var client = new AmazonSimpleEmailServiceClient("YourAWSAccessKeyID", "YourAWSSecretAccessKey", RegionEndpoint.USEast1))
         using (var messageStream = new MemoryStream())
         {
             var message = new MimeMessage();
             var builder = new BodyBuilder()
             {
                 TextBody = "Hello World"
             };
             message.From.Add(new MailboxAddress("*****@*****.**"));
             message.To.Add(new MailboxAddress("*****@*****.**"));
             message.Subject = "Hello World";
             //I'm using the stream method, but you don't have to.
             using (FileStream stream = File.Open(@"Attachment1.pdf", FileMode.Open)) builder.Attachments.Add("Attachment1.pdf", stream);
             using (FileStream stream = File.Open(@"Attachment2.pdf", FileMode.Open)) builder.Attachments.Add("Attachment2.pdf", stream);
             message.Body = builder.ToMessageBody();
             message.WriteTo(messageStream);
             var request = new SendRawEmailRequest()
             {
                 RawMessage = new RawMessage()
                 {
                     Data = messageStream
                 }
             };
             client.SendRawEmail(request);
         }
 }
Пример #19
0
 public AmazonSESProviderService(IOptions <ConfigOptions> emailProvidersConfig, ILogger <AmazonSESProviderService> logger)
 {
     _logger = logger;
     // TODO: Remove redundant method call
     _awsSES = new AmazonSimpleEmailServiceClient(emailProvidersConfig.Value.EmailProviders.AmazonSES.KeyId,
                                                  emailProvidersConfig.Value.EmailProviders.AmazonSES.KeySecret, RegionEndpoint.EUWest1);
 }
Пример #20
0
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task FunctionHandler(string input, ILambdaContext context)
        {
            IAmazonSQS              sqsClient              = new AmazonSQSClient();
            ISqsAdapter             sqsAdapter             = new SqsAdapter(sqsClient, "");
            IAmazonS3               s3Client               = new AmazonS3Client();
            IS3Adapter              s3Adapter              = new S3Adapter(s3Client);
            IEmailMessageRepository emailMessageRepository = new EmailMessageRepository(sqsAdapter, s3Adapter);

            IAmazonSimpleEmailService sesClient   = new AmazonSimpleEmailServiceClient();
            IEmailDeliveryConfig      emailConfig = new EmailDeliveryConfig()
            {
                FromAddress = ""
            };
            ISESAdapter           sesAdapter      = new SESAdapter(sesClient, emailConfig);
            IEmailMessageDelivery messageDelivery = new EmailMessageDelivery(sesAdapter);
            IEmailQueueProcessor  emailProcessor  = new EmailQueueProcessor(emailMessageRepository, messageDelivery);

            var emptyProcesses = 0;

            while (emptyProcesses <= 3 && context.RemainingTime > TimeSpan.FromSeconds(30))
            {
                var count = await emailProcessor.ProcessEmailMessages();

                if (count == 0)
                {
                    emptyProcesses++;
                }
            }
        }
Пример #21
0
        public void ConfigureDevelopmentServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // Add S3 to the ASP.NET Core dependency injection framework.
            var settings = new LocalWindowsEnvironmentSettings(Configuration);

            services.AddSingleton <IEnvironmentSettings>(settings);

            var s3 = new Amazon.S3.AmazonS3Client(settings.AWSAccessKey, settings.AWSSecret, Amazon.RegionEndpoint.USWest2);

            services.AddSingleton <IAmazonS3>(s3);

            var emailService = new AmazonSimpleEmailServiceClient(settings.AWSAccessKey, settings.AWSSecret, Amazon.RegionEndpoint.USWest2);

            //var emailClient = new Mock<IAmazonSimpleEmailService>();
            //emailClient.Setup(e => e.SendEmailAsync(It.IsAny<SendEmailRequest>(), new System.Threading.CancellationToken()))
            //    .Callback<SendEmailRequest, System.Threading.CancellationToken>((req, token) =>
            //      {
            //          Console.WriteLine("Email Sent:");
            //          Console.WriteLine(req.Message.Body);
            //      })
            //    .Returns(Task.FromResult(new SendEmailResponse()));
            services.AddSingleton <IAmazonSimpleEmailService>(emailService);
        }
Пример #22
0
        public async Task SendEmail(EmailDto email)
        {
            using var client = new AmazonSimpleEmailServiceClient(_key, _secret, RegionEndpoint.APSouth1);
            var sendRequest = new SendEmailRequest
            {
                Source      = email.SenderAddress,
                Destination = new Destination
                {
                    ToAddresses = new List <string> {
                        email.ReceiverAddress
                    }
                },
                Message = new Message
                {
                    Subject = new Content(email.Subject),
                    Body    = new Body
                    {
                        Text = new Content
                        {
                            Charset = "UTF-8",
                            Data    = email.TextBody
                        }
                    }
                }
            };

            await client.SendEmailAsync(sendRequest);
        }
Пример #23
0
        public AWSEmail()
        {
            var accessKey = ConfigurationManager.AppSettings["ses.accessKey"];
            var secretKey = ConfigurationManager.AppSettings["ses.secretKey"];

            _emailService = new AmazonSimpleEmailServiceClient(accessKey, secretKey);
        }
Пример #24
0
        /// <summary>
        /// Asynchronously sends the provided IdentityMessage.
        /// </summary>
        /// <param name="message">The message to send.</param>
        /// <remarks>
        /// Sends the provided message using Amazon's Simple Email Service Client.
        ///
        /// If it is passed on ApplicationMessage, it will use it to populate
        /// both the HTML body and the plain text body.  Otherwise, it will only
        /// populate the message body and let Amazon SES work out how to format
        /// it properly.
        ///
        /// Requires environment variable AWS_ACCESS_KEY_ID.
        /// </remarks>
        public Task SendAsync(IdentityMessage message)
        {
            var subject = new Content(message.Subject);

            var applicationMessage = message as ApplicationMessage;

            var body = new Body {
                Text = new Content(message.Body)
            };

            if (applicationMessage != null)
            {
                body.Html = new Content(applicationMessage.HtmlBody);
            }

            var toEmail = new Destination(new List <string> {
                message.Destination
            });

            var email   = new Message(subject, body);
            var request = new SendEmailRequest(FromEmail, toEmail, email);
            var region  = Amazon.RegionEndpoint.EUWest1;

            var client = new AmazonSimpleEmailServiceClient(region);

            client.SendEmail(request);

            return(Task.FromResult(0));
        }
Пример #25
0
        async static Task <List <SendDataPoint> > GetSesStatsForAccount(string Account)
        {
            string strRoleARN = "arn:aws:iam::" + Account + ":role/" + AssumedRoleName;

            Amazon.SecurityToken.AmazonSecurityTokenServiceClient stsClient = new Amazon.SecurityToken.AmazonSecurityTokenServiceClient();
            var assumeRoleResponse = await stsClient.AssumeRoleAsync(new Amazon.SecurityToken.Model.AssumeRoleRequest {
                RoleArn = strRoleARN, RoleSessionName = "TempSession"
            });


            SessionAWSCredentials sessionCredentials =
                new SessionAWSCredentials(assumeRoleResponse.Credentials.AccessKeyId,
                                          assumeRoleResponse.Credentials.SecretAccessKey,
                                          assumeRoleResponse.Credentials.SessionToken);

            var regions = new Amazon.RegionEndpoint[] { Amazon.RegionEndpoint.USEast1, Amazon.RegionEndpoint.USWest2, Amazon.RegionEndpoint.EUWest1 };

            List <SendDataPoint> lst = new List <SendDataPoint>();

            foreach (var region in regions)
            {
                Console.WriteLine($"Checking {region.ToString()} for account {Account}");

                AmazonSimpleEmailServiceClient sesClient = new AmazonSimpleEmailServiceClient(sessionCredentials, region);

                var response = await sesClient.GetSendStatisticsAsync();

                lst.AddRange(response.SendDataPoints);
            }

            return(lst);
        }
Пример #26
0
        public async Task SendEmailsAsync(IEnumerable <string> emails, string subject, string message)
        {
            _logger.LogInformation("sending email to {0} with subject {1}", string.Join(", ", emails), subject);

            SendEmailRequest emailRequest = new SendEmailRequest()
            {
                Source      = _authOptions.FromAddress,
                Destination = new Destination(emails.ToList()),
                Message     = new Message()
                {
                    Body = new Body()
                    {
                        Html = new Content(message)
                    },
                    Subject = new Content(subject)
                }
            };

            AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(_authOptions.SesAwsAccessKeyID, _authOptions.SesAwsAccessKey, _authOptions.Region);

            try
            {
                SendEmailResponse response = await client.SendEmailAsync(emailRequest);

                _logger.LogInformation("successfully send email to {0}", string.Join(", ", emails));
            }
            catch (Exception e)
            {
                _logger.LogError("failed to send email to {0} with error {1}", string.Join(", ", emails), e);
            }
        }
Пример #27
0
        private async Task <bool> SendMessage(CognitoAWSCredentials creds, RegionEndpoint region)
        {
            bool result;

            try
            {
                AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(creds, region);

                var mailRequest = new SendEmailRequest
                {
                    Destination = new Destination
                    {
                        /*    BccAddresses = new List<string>
                         *  {
                         *      "*****@*****.**"
                         *  },
                         *  CcAddresses = new List<string> {
                         *      "*****@*****.**"
                         *  },*/
                        ToAddresses = new List <string> {
                            ToEMailTextBox.Text
                        }
                    },
                    Message = new Amazon.SimpleEmail.Model.Message
                    {
                        Body = new Body
                        {
                            Html = new Content {
                                Charset = "UTF-8",
                                Data    = MessageTextBox.Text
                            },
                            Text = new Content {
                                Charset = "UTF-8",
                                Data    = "This is the message body in text format."
                            }
                        },
                        Subject = new Content {
                            Charset = "UTF-8",
                            Data    = SubjectTextBox.Text
                        }
                    },
                    ReplyToAddresses = new List <string> {
                        ReplyToEMailTextBox.Text
                    },
                    Source = "*****@*****.**"
                };
                var response = await client.SendEmailAsync(mailRequest);;

                string messageId = response.MessageId;

                result = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                result = false;
            }

            return(result);
        }
Пример #28
0
 public override void Init(IDictionary <string, string> properties)
 {
     base.Init(properties);
     ses            = new AmazonSimpleEmailServiceClient(properties["accessKey"], properties["secretKey"]);
     refreshTimeout = TimeSpan.Parse(properties.ContainsKey("refreshTimeout") ? properties["refreshTimeout"] : "0:30:0");
     lastRefresh    = DateTime.UtcNow - refreshTimeout; //set to refresh on first send
 }
Пример #29
0
        public Task SendEmailAsync(string email, string subject, string message)
        {
            using var client = new AmazonSimpleEmailServiceClient(this.Options.RegionEndpoint);
            var sendRequest = new SendEmailRequest
            {
                Source      = this.Options.SenderAddress,
                Destination = new Destination
                {
                    ToAddresses = new List <string> {
                        email
                    }
                },
                Message = new Message
                {
                    Subject = new Content(subject),
                    Body    = new Body
                    {
                        Html = new Content {
                            Charset = "UTF-8", Data = message
                        },
                        Text = new Content {
                            Charset = "UTF-8", Data = message
                        }
                    }
                },
                // todo ConfigurationSetNameについて調査
                // ConfigurationSetName = configSet
            };

            return(client.SendEmailAsync(sendRequest));
        }
Пример #30
0
        public async Task <bool> SendEmail(MailMessage email)
        {
            var accessKey = _config["AWS:SES:AccessKeyId"];
            var secret    = _config["AWS:SES:AccessKeySecret"];
            var creds     = new BasicAWSCredentials(accessKey, secret);

            using (var client = new AmazonSimpleEmailServiceClient(creds, RegionEndpoint.USEast1))
            {
                var req = new SendEmailRequest()
                {
                    Source      = email.From.Address,
                    Destination = new Destination()
                    {
                        ToAddresses = email.To.Select(e => e.Address).ToList()
                    },
                    Message = ReformatToAWSMessage(email),
                };

                try
                {
                    var response = await client.SendEmailAsync(req);

                    return(true);
                }
                catch (Exception e)
                {
                    return(false);
                }
            }
        }