Represents the message to be sent, composed of a subject and a body.

Exemple #1
0
    public static void SESSendEmail()
    {
      #region SESSendEmail
      var sesClient = new AmazonSimpleEmailServiceClient();           
      
      var dest = new Destination
      {
        ToAddresses = new List<string>() { "*****@*****.**" },
        CcAddresses = new List<string>() { "*****@*****.**" }
      };

      var from = "*****@*****.**";
      var subject = new Content("You're invited to the meeting");
      var body = new Body(new Content("Please join us Monday at 7:00 PM."));
      var msg = new Message(subject, body);

      var request = new SendEmailRequest
      {
        Destination = dest,
        Message = msg, 
        Source = from
      };

      sesClient.SendEmail(request);
      #endregion
    }
        public Task<bool> SendEmail(string to, string subject, string htmlBody)
        {
            if (string.IsNullOrEmpty(subject) || string.IsNullOrEmpty(htmlBody) || !to.IsEmail()) return Task.FromResult(false);

            var destination = new Destination { ToAddresses = new List<string> { to } };

            var contentSubject = new Content { Charset = Encoding.UTF8.EncodingName, Data = subject };
            var contentBody = new Content { Charset = Encoding.UTF8.EncodingName, Data = htmlBody };
            var body = new Body { Html = contentBody };

            var message = new Message { Body = body, Subject = contentSubject };

            var request = new SendEmailRequest
            {
                Source = FROM_EMAIL,
                Destination = destination,
                Message = message
            };

            var client = new AmazonSimpleEmailServiceClient();

            try
            {
                client.SendEmail(request);
            }
            catch (Exception ex)
            {
               return Task.FromResult(false);
            }

            return Task.FromResult(true);
        }
Exemple #3
0
        public void Send(string name, string replyTo, string messageBody)
        {
            var destination = new Destination()
            {
                ToAddresses = new List<string>() { TO }
            };

            var subject = new Content(SUBJECT);

            var body = new Body()
            {
                Html = new Content(string.Format(BODY, name, messageBody))
            };

            var message = new Message(subject, body);

            var request = new SendEmailRequest(FROM, destination, message);

            request.ReplyToAddresses = new List<string> { replyTo };

            var region = Amazon.RegionEndpoint.USEast1;

            using (var client = new AmazonSimpleEmailServiceClient(region))
            {
                try
                {
                    client.SendEmail(request);
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
 public void SendEmail(string to, string subject, string bodyText, string bodyHtml)
 {
     using (var client = new AmazonSimpleEmailServiceClient(RegionEndpoint.EUWest1))
     {
         var content = new Content(subject);
         var body = new Body{Html = new Content(bodyHtml), Text = new Content(bodyText)};
         var message = new Message(content, body);
         var destination = new Destination(new List<string> {to});
         var sendEmailRequest = new SendEmailRequest(FromEmail, destination, message);
         client.SendEmail(sendEmailRequest);
     }
 }
        public void Send(string from, IEnumerable<string> to, IEnumerable<string> bcc, string subject, string body)
        {
            var bodyContent = new Content(body)
            {
                Charset = "UTF-8"
            };

            var message = new Message(new Content(subject), new Body { Html = bodyContent });

            var destinations = new List<Destination>();
            var destination = new Destination();

            if (to != null)
            {
                foreach (var email in to)
                {
                    if(string.IsNullOrEmpty(email))
                        throw new ArgumentException("To Email can not be null or empty");

                    destination.ToAddresses.Add(email);

                    if (destination.ToAddresses.Count != _sender.MaxRecipientPerBatch) continue;

                    destinations.Add(destination);
                    destination = new Destination();
                }
            }

            if (bcc != null)
            {
                foreach (var email in bcc)
                {
                    if (string.IsNullOrEmpty(email))
                        throw new ArgumentException("Bbc Email can not be null or empty");

                    destination.BccAddresses.Add(email);

                    if (destination.ToAddresses.Count + destination.BccAddresses.Count != _sender.MaxRecipientPerBatch) continue;

                    destinations.Add(destination);
                    destination = new Destination();
                }
            }

            if (destination.ToAddresses.Count + destination.BccAddresses.Count != 0)
                destinations.Add(destination);

            foreach (var d in destinations)
                _sender.Send(new SendEmailRequest(from, d, message));
        }
        protected override void Write(LogEventInfo logEvent)
        {
            var logMessage = this.Layout.Render(logEvent);

            // Queue up the message
            var message = new Message();
            message.WithBody(new Body
            {
                Text = new Content { Charset = "UTF-8", Data = logMessage }
                //,Html = new Content { Charset = "UTF-8", Data = logMessage }
            });
            message.WithSubject(new Content { Charset = "UTF-8", Data = Subject.Render(logEvent) });
            _queue.Enqueue(message);

            StartMta();
        }
Exemple #7
0
        private void button2_Click(object sender, EventArgs e)
        {
            string AccessKey= System.Configuration.ConfigurationManager.AppSettings["AccessKey"];
            string SecrectKey = System.Configuration.ConfigurationManager.AppSettings["SecrectKey"];
            Amazon.SimpleEmail.AmazonSimpleEmailServiceClient mailClient = new Amazon.SimpleEmail.AmazonSimpleEmailServiceClient(AccessKey,SecrectKey);
            //var obj = mailClient.GetSendQuota();
            SendEmailRequest request = new SendEmailRequest();
            List<string> toaddress = new List<string>();
            toaddress.Add("*****@*****.**");
            Destination des = new Destination(toaddress);
            request.Destination = des;
            request.Source = "*****@*****.**";
            Amazon.SimpleEmail.Model.Message mes = new Amazon.SimpleEmail.Model.Message();
            mes.Body = new Body(new Content( @"Hiện tại, Windows Phone mới hỗ trợ đến màn hình full HD, do đó để tương thích với màn hình 2K, hệ điều hành chắc chắn phải có bản cập nhật mới. Mặt khác, vi xử lý Snapdragon 805 của Qualcomm được biết sẽ phát hành đại trà vào nửa sau năm nay, nên thời điểm xuất hiện Lumia 1820 dùng vi xử lý này tại MWC 2014 vào tháng Hai sẽ là dấu hỏi lớn.

            Microsoft đã từng nói hãng đã chi tới 2,6 tỉ USD để phát triển cho hệ điều hành Windows Phone. Và năm nay, Microsoft đang có kế hoạch lớn dành cho Windows Phone lẫn Nokia. Do đó, chúng ta hãy cứ hy vọng Lumia 1525 và Lumia 1820 sẽ là bom tấn smartphone được kích hoạt trong 2014 này."));
            mes.Subject = new Content("Test send via amazon");

            request.Message = mes;

            SendEmailResponse response = mailClient.SendEmail(request);
            var messageId = response.SendEmailResult.MessageId;
            /*GetIdentityNotificationAttributesRequest notifyRequest = new GetIdentityNotificationAttributesRequest();
            List<string> iden = new List<string>();
            iden.Add("*****@*****.**"); //iden.Add(response.ResponseMetadata.RequestId);
            notifyRequest.Identities = iden;
            var notify = mailClient.GetIdentityNotificationAttributes(notifyRequest);
            //MessageBox.Show(notify.GetIdentityNotificationAttributesResult.NotificationAttributes["Bounces"].BounceTopic);

            var temp = mailClient.GetSendStatistics();
            MessageBox.Show("Total: "+temp.GetSendStatisticsResult.SendDataPoints.Count+"\nDeliveryAttempts: "+temp.GetSendStatisticsResult.SendDataPoints[265].DeliveryAttempts+"\n"
                + "Complaints: " + temp.GetSendStatisticsResult.SendDataPoints[265].Complaints + "\n"
                + "Bounces: " + temp.GetSendStatisticsResult.SendDataPoints[265].Bounces + "\n"
                + "Rejects: " + temp.GetSendStatisticsResult.SendDataPoints[265].Rejects + "\n");
               // MessageBox.Show("Max24HourSend:" + obj.GetSendQuotaResult.Max24HourSend + "\nMaxSendRate:" + obj.GetSendQuotaResult.MaxSendRate + "\nSentLast24Hours:" + obj.GetSendQuotaResult.SentLast24Hours);

            Amazon.SimpleNotificationService.Model.GetEndpointAttributesRequest endpointRequest = new Amazon.SimpleNotificationService.Model.GetEndpointAttributesRequest();
            Amazon.SimpleNotificationService.AmazonSimpleNotificationServiceClient notifyClient = new Amazon.SimpleNotificationService.AmazonSimpleNotificationServiceClient();
            //string result = notifyClient.GetEndpointAttributes(notify).GetEndpointAttributesResult.ToXML();
            //MessageBox.Show(result);
            */
            Amazon.SQS.AmazonSQSClient client = new Amazon.SQS.AmazonSQSClient(AccessKey, SecrectKey);
            Amazon.SQS.Model.ReceiveMessageRequest SQSrequest = new Amazon.SQS.Model.ReceiveMessageRequest();
            SQSrequest.MaxNumberOfMessages = 10;
            SQSrequest.QueueUrl = "https://sqs.us-east-1.amazonaws.com/063719400628/bounce-queue";
            AmazonQueues.ProcessQueuedBounce(client.ReceiveMessage(SQSrequest));
        }
        protected override void Write(AsyncLogEventInfo[] logEvents)
        {
            var logMessage = logEvents.Aggregate(string.Empty,
                                (current, logEvent) => current + string.Format("{0}{1}", this.Layout.Render(logEvent.LogEvent), Environment.NewLine));

            // Queue up the message
            var message = new Message();
            message.WithBody(new Body
            {
                Text = new Content { Charset = "UTF-8", Data = logMessage }
                //,Html = new Content { Charset = "UTF-8", Data = logMessage }
            });
            message.WithSubject(new Content { Charset = "UTF-8", Data = Subject.Render(logEvents[logEvents.Length - 1].LogEvent) });
            _queue.Enqueue(message);

            StartMta();
        }
Exemple #9
0
        /// <summary>
        ///     Sends an email with opt out option
        /// </summary>
        /// <param name="fromEmail"></param>
        /// <param name="toEmail"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        public bool SendMail(string fromEmail, string toEmail, string subject, string body)
        {
            if (string.IsNullOrEmpty(toEmail) ||
                string.IsNullOrEmpty(fromEmail) ||
                string.IsNullOrEmpty(subject) ||
                string.IsNullOrEmpty(body)) return false;

            try
            {
                toEmail = toEmail.Trim();
                fromEmail = fromEmail.Trim();

                var amzClient = new AmazonSimpleEmailServiceClient(
                    AmazonCloudConfigs.AmazonAccessKey, AmazonCloudConfigs.AmazonSecretKey, RegionEndpoint.USEast1);
                var dest = new Destination();
                dest.ToAddresses.Add(toEmail);

                body =
                    body +
                    Environment.NewLine +
                    Environment.NewLine +
                    Environment.NewLine +
                    Environment.NewLine +
                    Environment.NewLine +
                    "----------------------------" +
                    Environment.NewLine +
                    "Unsubscribe From Email: " + // TODO: LOCALIZE
                    Environment.NewLine +
                    GeneralConfigs.EmailSettingsURL +
                    Environment.NewLine;

                var bdy = new Body {Text = new Content(body)};
                var title = new Content(subject);
                var message = new Message(title, bdy);
                fromEmail = string.Format("{0} <{1}>", GeneralConfigs.SiteName, fromEmail);
                var ser = new SendEmailRequest(fromEmail, dest, message);

                var response = amzClient.SendEmail(ser);

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
 /// <summary>
 /// The send mail.
 /// </summary>
 /// <param name="from">
 /// The from.
 /// </param>
 /// <param name="to">
 /// The to.
 /// </param>
 /// <param name="subject">
 /// The subject.
 /// </param>
 /// <param name="body">
 /// The body.
 /// </param>
 public void SendMail(string @from, string to, string subject, string body)
 {
     using (var client = Amazon.AWSClientFactory.CreateAmazonSimpleEmailServiceClient(this.credentials))
     {
         var request = new SendEmailRequest();
         var destination = new Destination(to.Split(';', ',').ToList());
         request.WithDestination(destination);
         request.WithSource(@from);
         var message = new Message();
         message.WithSubject(new Content(subject));
         var html = new Body { Html = new Content(body) };
         message.WithBody(html);
         request.WithMessage(message);
         request.WithReturnPath("*****@*****.**");
         client.SendEmail(request);
     }
 }
        public static string ProcessRequest(AbsenceModel absenceModel)
        {
            try
            {
                const String from = "*****@*****.**";
                // Construct an object to contain the recipient address.
                Destination destination = new Destination();
                destination.ToAddresses = (new List <string>()
                {
                    ""
                });
                Content emailSubject = new Content("asdasd");
                Content textBody     = new Content("asdsad");
                Body    body         = new Body();
                body.Html = textBody;
                // Create a message with the specified subject and body.
                Amazon.SimpleEmail.Model.Message message      = new Amazon.SimpleEmail.Model.Message(emailSubject, body);
                SendEmailRequest               request        = new SendEmailRequest(from, destination, message);
                Amazon.RegionEndpoint          regionEndPoint = Amazon.RegionEndpoint.USWest2;
                AmazonSimpleEmailServiceConfig config         = new AmazonSimpleEmailServiceConfig();
                config.RegionEndpoint = regionEndPoint;
                var key = "AKIAISEURJBJ3YL4J6EA";
                var sec = "7iiVlPs51EEoZw5+TjlE+z/XdEy9WCa0rvF91u6O";
                // Instantiate an Amazon SES client, which will make the service call.
                AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(key, sec, config);
                client.SendEmailAsync(request);
            }

            catch (Exception ex)
            {
                //log into database.

                string exception = "Email Sending Failed Amazon SES";
                if (ex.StackTrace != null)
                {
                    exception = exception + "Main Stack Trace: " + ex.StackTrace;
                    exception = exception + " Main Message " + Convert.ToString(ex.Message);
                }
                if (ex.InnerException != null)
                {
                    exception = exception + "Inner Stack Trace: " + ex.StackTrace;
                    exception = exception + " Inner Message " + Convert.ToString(ex.Message);
                }
            }
            return("");
        }
Exemple #12
0
        public void Enviar()
        {
            var body = new Body().WithText(new Content(_log.ToString()));
            var mess = new Message(
                new Content("Backup " + DateTime.Now.ToString("dd/MM/yyyy hh:mm")),
                body);
            var req = new SendEmailRequest("*****@*****.**",
                                           new Destination().WithToAddresses(_destinos),
                                           mess);

            try
            {
                _client.SendEmail(req);
            }
            catch(Exception ex)
            {
                Console.Out.Write(_log.ToString());
            }
        }
Exemple #13
0
        public async Task SendAsync(SendEmailModel sendEmailModel)
        {
            var from = sendEmailModel.FromEmail;

            if (string.IsNullOrWhiteSpace(from))
            {
                from = ConfigurationManager.AppSettings["aws:fromEmail"];
            }

            var destination = new Destination
            {
                ToAddresses  = sendEmailModel.Emails,
                BccAddresses = sendEmailModel.BccEmails
            };
            Content subject  = new Content(sendEmailModel.Subject);
            Content textBody = new Content(sendEmailModel.Body);
            Body    body     = new Body
            {
                Html = textBody
            };
            var message = new Amazon.SimpleEmail.Model.Message(subject, body);

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

            if (!string.IsNullOrWhiteSpace(sendEmailModel.ReplyTo))
            {
                request.ReplyToAddresses = new List <string>();
                request.ReplyToAddresses.Add(sendEmailModel.ReplyTo);
            }
            var clientId  = ConfigurationManager.AppSettings["aws:ClientId"];
            var secretKey = ConfigurationManager.AppSettings["aws:SecretKey"];
            var sesRegion = ConfigurationManager.AppSettings["aws:SesRegion"];

            AWSCredentials credentials = new BasicAWSCredentials(clientId,
                                                                 secretKey);

            RegionEndpoint region = RegionEndpoint.GetBySystemName(sesRegion);

            AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(credentials, region);

            await client.SendEmailAsync(request);
        }
 public Task<string> Send(IEnumerable<string> to, IEnumerable<string> cc, string from, string title, string htmlBody, string textBody)
 {
     AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(_accessKey, _secretKey);
     Destination destination = new Destination();
     destination.ToAddresses = to.ToList();
     Content subject = new Content(title);
     Body bodyContent = new Body()
     {
         Html = htmlBody == null ? null : new Content(htmlBody),
         Text = textBody == null ? null : new Content(textBody)
     };
     Message message = new Message(subject, bodyContent);
     SendEmailRequest request = new SendEmailRequest
     {
         ReplyToAddresses = new List<string>() {@from},
         Destination = destination,
         Message = message
     };
     SendEmailResponse response = client.SendEmail(request);
     return Task.FromResult(response.MessageId);
 }
        /// <summary>
        ///     <see cref="Send" /> the email message to Amazon's Simple Email Service.
        /// </summary>
        /// <returns>true if it succeeds, false if it fails.</returns>
        internal bool Send()
        {
            _email.MessageId = string.Empty;

            try
            {
                var message = new Message
                {
                    Body =
                        _email.HTML
                            ? new Body().WithHtml(new Content(_email.MessageBody)) : new Body().WithText(new Content(_email.MessageBody)),
                    Subject = new Content(_email.MessageSubject)
                };
                var request = new SendEmailRequest(_email.FromAddress, _email.Destination, message);
                using (var client = new Client(_email.Credentials))
                {
                    _email.MessageId = client.SendFormattedEmail(request);
                }

                return !_email.ErrorExists;
            }
            catch (AmazonSimpleEmailServiceException ex)
            {
                return _email.SetErrorMessage(
                    string.Format(
                        "AWS Simple Email Service Exception\n\nError Type: {0}\n" +
                        "Error Code: {1}\nRequest Id: {2}\nStatus Code: {3}\n\n{4}",
                        ex.ErrorType, ex.ErrorCode, ex.RequestId, ex.StatusCode, ex));
            }
            catch (AmazonClientException ex)
            {
                return _email.SetErrorMessage(ex.ToString());
            }
            catch (Exception ex)
            {
                return _email.SetErrorMessage(ex.ToString());
            }
        }
        private Message BuildMessage(Indulgence indulgence)
        {
            var templateDoc = XDocument.Load(HostingEnvironment.MapPath("~/content/emailTemplates/indulgenceEmail.xml"));
            string subjectText = templateDoc.Element("email").Element("subject").Value;
            string textBody = templateDoc.Element("email").Element("body").Element("text").Value;
            string htmlBody = templateDoc.Element("email").Element("body").Element("html").Value;
            subjectText = subjectText
                .Replace("@DonorName", indulgence.Name)
                .Replace("@CharityName", indulgence.CharityName);
            textBody = textBody
                .Replace("@DonorName", indulgence.Name)
                .Replace("@CharityName", indulgence.CharityName);
            htmlBody = htmlBody
                .Replace("@DonorName", indulgence.Name)
                .Replace("@CharityName", indulgence.CharityName);

            Content subject = new Content();
            subject.Charset = "utf-8";
            subject.Data = subjectText;

            Content html = new Content();
            html.Charset="UTF-8";
            html.Data= htmlBody;

            Content text = new Content();
            text.Charset="UTF-8";
            text.Data=textBody;

            Body body = new Body();
            body.Html=html;
            body.Text=text;

            Message message = new Message();
            message.Body=body;
            message.Subject=subject;

            return message;
        }
Exemple #17
0
        private ASM.Message CreateMessage(IEmailMessage message)
        {
            string subjectText = !string.IsNullOrEmpty(message.Subject) ? message.Subject : "General enquiry";
            var    subject     = new ASM.Content();

            subject.Charset = _charset;
            subject.Data    = subjectText;

            var text = new ASM.Content();

            text.Charset = _charset;
            text.Data    = message.Text;

            var body = new ASM.Body();

            body.Text = text;

            var awsMessage = new ASM.Message();

            awsMessage.Body    = body;
            awsMessage.Subject = subject;

            return(awsMessage);
        }
 public async Task SendAsync(string htmlBody, string subject, string[] to, string from, bool isHtmlBody, string base64, string charset = "utf-8")
 {
     try
     {
         // Construct an object to contain the recipient address.
         Destination destination = new Destination();
         destination.ToAddresses = (new List <string>()
         {
             to.FirstOrDefault()
         });
         // Create the subject and body of the message.
         Content emailSubject = new Content(subject);
         Content textBody     = new Content(htmlBody);
         Body    body         = new Body();
         body.Html = textBody;
         Amazon.SimpleEmail.Model.Message message = new Amazon.SimpleEmail.Model.Message(emailSubject, body);
         SendEmailRequest request = new SendEmailRequest(from, destination, message);
         await ExecuteAsync(request);
     }
     catch (FormatException e)
     {
         throw new SmtpException("ErrorOnSend", e);
     }
 }
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // 尝试注册用户
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    //Send email by amazon ses
                    string accessKey = "AKIAIO4BEQ2UGFAMHRFQ";
                    string secretAccessKey = "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";
                    AmazonSimpleEmailServiceConfig amazonConfiguration = new AmazonSimpleEmailServiceConfig();
                    AmazonSimpleEmailServiceClient clientMail = new AmazonSimpleEmailServiceClient(accessKey, secretAccessKey, amazonConfiguration);
                    Destination destination = new Destination();
                    destination.ToAddresses.Add(model.Email);
                    Body body = new Body() { Html = new Content("Welcome to AIRPDF "+"Your account is: "+model.UserName+" Your password is: "+model.ConfirmPassword) };
                    Content subject = new Content("Welcome to AIRPDF!");
                    Message message = new Message(subject, body);
                    SendEmailRequest sendEmailRequest = new SendEmailRequest("*****@*****.**", destination, message);
                    clientMail.SendEmail(sendEmailRequest);

                    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "pdf");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // 如果我们进行到这一步时某个地方出错,则重新显示表单
            return View(model);
        }
 public SendEmailRequest WithMessage(Message message)
 {
     this.message = message;
     return this;
 }
 /// <summary>
 /// Constructs a new SendEmailRequest object.
 /// Callers should use the properties or fluent setter (With...) methods to
 /// initialize any additional object members.
 /// </summary>
 /// 
 /// <param name="source"> The identity's email address. </param>
 /// <param name="destination"> The destination for this email, composed of To:, CC:, and BCC: fields. </param>
 /// <param name="message"> The message to be sent. </param>
 public SendEmailRequest(string source, Destination destination, Message message)
 {
     this.source = source;
     this.destination = destination;
     this.message = message;
 }
Exemple #22
0
        ///<Summary>
        /// Gets the answer
        ///</Summary>
        public static Boolean SendEmail(String From, String To, String Subject, String Text = null, String HTML = null, String emailReplyTo = null, String returnPath = null)
        {
            if (Text != null && HTML != null)
            {
                String from = From;

                List<String> to
                    = To
                    .Replace(", ", ",")
                    .Split(',')
                    .ToList();

                Destination destination = new Destination();
                destination.WithToAddresses(to);
                //destination.WithCcAddresses(cc);
                //destination.WithBccAddresses(bcc);

                Amazon.SimpleEmail.Model.Content subject = new Amazon.SimpleEmail.Model.Content();
                subject.WithCharset("UTF-8");
                subject.WithData(Subject);

                Amazon.SimpleEmail.Model.Content html = new Amazon.SimpleEmail.Model.Content();
                html.WithCharset("UTF-8");
                html.WithData(HTML);

                Amazon.SimpleEmail.Model.Content text = new Amazon.SimpleEmail.Model.Content();
                text.WithCharset("UTF-8");
                text.WithData(Text);

                Body body = new Body();
                body.WithHtml(html);
                body.WithText(text);

                Amazon.SimpleEmail.Model.Message message = new Amazon.SimpleEmail.Model.Message();
                message.WithBody(body);
                message.WithSubject(subject);

                AmazonSimpleEmailService ses = AWSClientFactory.CreateAmazonSimpleEmailServiceClient(AppConfig["AWSAccessKey"], AppConfig["AWSSecretKey"]);

                SendEmailRequest request = new SendEmailRequest();
                request.WithDestination(destination);
                request.WithMessage(message);
                request.WithSource(from);

                if (emailReplyTo != null)
                {
                    List<String> replyto
                        = emailReplyTo
                        .Replace(", ", ",")
                        .Split(',')
                        .ToList();

                    request.WithReplyToAddresses(replyto);
                }

                if (returnPath != null)
                {
                    request.WithReturnPath(returnPath);
                }

                try
                {
                    SendEmailResponse response = ses.SendEmail(request);

                    SendEmailResult result = response.SendEmailResult;

                    return true;
                }
                catch
                {
                    return false;
                }
            }

            return false;
        }
        //Send notification to user via email.
        /// <summary>
        /// Uses SES to send an email to a user.
        /// </summary>
        /// <param name="email">The email.</param>
        private void SendEmail(String email)
        {
            try
            {
                String[] arrayTO = new String[1];
                arrayTO[0] = email;

                List<string> listTO = arrayTO.ToList<String>();

                // Construct an object to contain the recipient address.
                Destination destination = new Destination().WithToAddresses(listTO);

                String FROM = "*****@*****.**";
                String SUBJECT = "Welcome to Cookbook!";
                String BODY = "Welcome to Cookbook! Thank you so much for joining us. We hope that you will enjoy using our website.";

                // Create the subject and body of the message.
                Content subject = new Content().WithData(SUBJECT);
                Content textBody = new Content().WithData(BODY);
                Body body = new Body().WithText(textBody);

                // Create a message with the specified subject and body.
                Message message = new Message().WithSubject(subject).WithBody(body);

                // Assemble the email.
                SendEmailRequest request = new SendEmailRequest().WithSource(FROM).WithDestination(destination).WithMessage(message);

                AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient();

                SendEmailResponse response = client.SendEmail(request);
                Console.WriteLine("Sent successfully.");

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        //Send notification to user via email.
        /// <summary>
        /// Uses SES to send an email to a user.
        /// </summary>
        /// <param name="userID">The user being sent the email</param>
        /// <param name="inputSubject">The subject of the email</param>
        /// <param name="inputBody">The body of the email</param>
        public static void SendEmail(int userID, string inputSubject, string inputBody)
        {
            try
            {
                String email = (from userprofiles in userDb.UserProfiles
                                where userprofiles.UserId == userID
                                select userprofiles.Email).FirstOrDefault(); ; //Find userID's email address.

                if (inputSubject == "")
                {
                    inputSubject = "The Cookbook - New Notification Waiting For You";
                }

                if (inputBody == "")
                {
                    inputBody = "You have received a new notification. Visit The Cookbook for more information.";
                }

                String[] arrayTO = new String[1];
                arrayTO[0] = email;

                List<string> listTO = arrayTO.ToList<String>();

                // Construct an object to contain the recipient address.
                Destination destination = new Destination().WithToAddresses(listTO);

                String FROM = "*****@*****.**";
                String SUBJECT = inputSubject;
                String BODY = inputBody;

                // Create the subject and body of the message.
                Content subject = new Content().WithData(SUBJECT);
                Content textBody = new Content().WithData(BODY);
                Body body = new Body().WithText(textBody);

                // Create a message with the specified subject and body.
                Message message = new Message().WithSubject(subject).WithBody(body);

                // Assemble the email.
                SendEmailRequest request = new SendEmailRequest().WithSource(FROM).WithDestination(destination).WithMessage(message);

                AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient();

                SendEmailResponse response = client.SendEmail(request);
                Console.WriteLine("Sent successfully.");

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Exemple #25
0
        ///<Summary>
        /// Gets the answer
        ///</Summary>
        public static Boolean SendEmail(String From, String To, String Subject, String Text = null, String HTML = null, String emailReplyTo = null, String returnPath = null)
        {
            if (Text != null && HTML != null)
            {
                String from = From;

                List <String> to
                    = To
                      .Replace(", ", ",")
                      .Split(',')
                      .ToList();

                Destination destination = new Destination();
                destination.WithToAddresses(to);
                //destination.WithCcAddresses(cc);
                //destination.WithBccAddresses(bcc);

                Amazon.SimpleEmail.Model.Content subject = new Amazon.SimpleEmail.Model.Content();
                subject.WithCharset("UTF-8");
                subject.WithData(Subject);

                Amazon.SimpleEmail.Model.Content html = new Amazon.SimpleEmail.Model.Content();
                html.WithCharset("UTF-8");
                html.WithData(HTML);

                Amazon.SimpleEmail.Model.Content text = new Amazon.SimpleEmail.Model.Content();
                text.WithCharset("UTF-8");
                text.WithData(Text);

                Body body = new Body();
                body.WithHtml(html);
                body.WithText(text);

                Amazon.SimpleEmail.Model.Message message = new Amazon.SimpleEmail.Model.Message();
                message.WithBody(body);
                message.WithSubject(subject);

                AmazonSimpleEmailService ses = AWSClientFactory.CreateAmazonSimpleEmailServiceClient(AppConfig["AWSAccessKey"], AppConfig["AWSSecretKey"]);

                SendEmailRequest request = new SendEmailRequest();
                request.WithDestination(destination);
                request.WithMessage(message);
                request.WithSource(from);

                if (emailReplyTo != null)
                {
                    List <String> replyto
                        = emailReplyTo
                          .Replace(", ", ",")
                          .Split(',')
                          .ToList();

                    request.WithReplyToAddresses(replyto);
                }

                if (returnPath != null)
                {
                    request.WithReturnPath(returnPath);
                }

                try
                {
                    SendEmailResponse response = ses.SendEmail(request);

                    SendEmailResult result = response.SendEmailResult;

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

            return(false);
        }
        /// <summary>
        /// Send the email message
        /// </summary>
        /// <param name="messageBody">the body text to include in the mail</param>
        protected virtual void SendEmail(string messageBody)
        {
            // Create the email object first, then add the properties.
            var subject = new Content(Subject);
            Body body = new Body();
            if (IsBodyHTML)
            {
                body.Html = new Content(messageBody);
            }
            else
            {
                body.Text = new Content(messageBody);
            }

            var destination = new Destination();
            var msg = new Message(subject, body);
            destination.ToAddresses = m_to.Split(ADDRESS_DELIMITERS).ToList();
            if (!String.IsNullOrWhiteSpace(m_cc))
            {
                destination.CcAddresses = m_cc.Split(ADDRESS_DELIMITERS).ToList();
            }
            if (!String.IsNullOrWhiteSpace(m_bcc))
            {
                destination.BccAddresses = m_bcc.Split(ADDRESS_DELIMITERS).ToList();
            }

            var request = new SendEmailRequest(From, destination, msg);
            var credentials = new Amazon.Runtime.BasicAWSCredentials(AccessKey, SecretKey);
            var client = new AmazonSimpleEmailServiceClient(credentials, Amazon.RegionEndpoint.EUWest1);

            try
            {
                client.SendEmailAsync(request);
            }
            catch (Exception ex)
            {
                ErrorHandler.Error("Error occurred while sending e-mail notification.", ex);
            }
        }
 /// <summary>
 /// Instantiates SendEmailRequest with the parameterized properties
 /// </summary>
 /// <param name="source">The email address that is sending the email. This email address must be either individually verified with Amazon SES, or from a domain that has been verified with Amazon SES. For information about verifying identities, see the <a href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-addresses-and-domains.html">Amazon SES Developer Guide</a>. If you are sending on behalf of another user and have been permitted to do so by a sending authorization policy, then you must also specify the <code>SourceArn</code> parameter. For more information about sending authorization, see the <a href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html">Amazon SES Developer Guide</a>.  In all cases, the email address must be 7-bit ASCII. If the text must contain any other characters, then you must use MIME encoded-word syntax (RFC 2047) instead of a literal string. MIME encoded-word syntax uses the following form: <code>=?charset?encoding?encoded-text?=</code>. For more information, see <a href="http://tools.ietf.org/html/rfc2047">RFC 2047</a>. </param>
 /// <param name="destination">The destination for this email, composed of To:, CC:, and BCC: fields.</param>
 /// <param name="message">The message to be sent.</param>
 public SendEmailRequest(string source, Destination destination, Message message)
 {
     _source = source;
     _destination = destination;
     _message = message;
 }
Exemple #28
0
        public static Boolean SendEmail(String From, String To, String Subject, String Text = null, String HTML = null, String emailReplyTo = null, String returnPath = null)
        {
            if (Text != null || HTML != null)
            {
                try
                {

                    String from = From;

                    List<String> to
                        = To
                            .Replace(", ", ",")
                            .Split(',')
                            .ToList();

                    Destination destination = new Destination();
                    destination.WithToAddresses(to);
                    //destination.WithCcAddresses(cc);
                    //destination.WithBccAddresses(bcc);

                    Content subject = new Content();
                    subject.WithCharset("UTF-8");
                    subject.WithData(Subject);

                    Body body = new Body();

                    if (HTML != null)
                    {
                        Content html = new Content();
                        html.WithCharset("UTF-8");
                        html.WithData(HTML);
                        body.WithHtml(html);
                    }

                    if (Text != null)
                    {
                        Content text = new Content();
                        text.WithCharset("UTF-8");
                        text.WithData(Text);
                        body.WithText(text);
                    }

                    Message message = new Message();
                    message.WithBody(body);
                    message.WithSubject(subject);

                    string awsAccessKey = AWSAccessKey;
                    string awsSecretKey = AWSSecretKey;
                    //AmazonSimpleEmailService ses = AWSClientFactory.CreateAmazonSimpleEmailServiceClient(AppConfig["AWSAccessKey"], AppConfig["AWSSecretKey"]);
                    AmazonSimpleEmailService ses = AWSClientFactory.CreateAmazonSimpleEmailServiceClient(awsAccessKey,
                                                                                                         awsSecretKey);

                    SendEmailRequest request = new SendEmailRequest();
                    request.WithDestination(destination);
                    request.WithMessage(message);
                    request.WithSource(from);

                    if (emailReplyTo != null)
                    {
                        List<String> replyto
                            = emailReplyTo
                                .Replace(", ", ",")
                                .Split(',')
                                .ToList();

                        request.WithReplyToAddresses(replyto);
                    }

                    if (returnPath != null)
                    {
                        request.WithReturnPath(returnPath);
                    }

                    SendEmailResponse response = ses.SendEmail(request);

                    SendEmailResult result = response.SendEmailResult;

                    Console.WriteLine("Email sent.");
                    Console.WriteLine(String.Format("Message ID: {0}",
                                                    result.MessageId));

                    return true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    //throw;
                    return false;
                }
                finally
                {
                    String queueMessage = String.Format("From: {1}{0}To: {2}{0}Subject: {3}{0}Message:{0}{4}",
                                                        Environment.NewLine, From, To, Subject, Text ?? HTML);
                    QueueSupport.CurrStatisticsQueue.AddMessage(new CloudQueueMessage(queueMessage));
                }
            }

            Console.WriteLine("Specify Text and/or HTML for the email body!");

            return false;
        }
Exemple #29
0
        public static Boolean SendEmail(String From, Recipient recipient, String Subject, String Text = null, 
            String HTML = null, String emailReplyTo = null, String returnPath = null)
        {
            if (Text != null && HTML != null)
            {
                String from = From;
                List<String> to = recipient.Email
                    .Replace(", ", ",")
                    .Split(',')
                    .ToList();

                Destination destination = new Destination();
                destination.WithToAddresses(recipient.Email);
                //destination.WithCcAddresses(cc);
                //destination.WithBccAddresses(bcc);

                Content subject = new Content();
                subject.WithCharset("UTF-8");
                subject.WithData(Subject);

                Content html = new Content();
                html.WithCharset("UTF-8");
                html.WithData(HTML);

                Content text = new Content();
                text.WithCharset("UTF-8");
                text.WithData(Text);

                Body body = new Body();
                body.WithHtml(html);
                body.WithText(text);

                Message message = new Message();
                message.WithBody(body);
                message.WithSubject(subject);

                string accessKey = ConfigurationManager.AppSettings["AWSAccessKey"];
                string secretKey = ConfigurationManager.AppSettings["AWSSecretKey"];

                AmazonSimpleEmailService ses = AWSClientFactory.CreateAmazonSimpleEmailServiceClient(accessKey, secretKey);
                SendEmailRequest request = new SendEmailRequest();
                request.WithDestination(destination);
                request.WithMessage(message);
                request.WithSource(from);

                if (emailReplyTo != null)
                {
                    List<String> replyto
                        = emailReplyTo
                        .Replace(", ", ",")
                        .Split(',')
                        .ToList();

                    request.WithReplyToAddresses(replyto);
                }

                if (returnPath != null)
                {
                    request.WithReturnPath(returnPath);
                }

                try
                {
                    SendEmailResponse response = ses.SendEmail(request);
                    SendEmailResult result = response.SendEmailResult;
                    return true;
                }
                catch (Exception ex)
                {
                    recipient.ErrorMessage = ex.Message;
                    return false;
                }
            }

            throw new Exception("Specify Text and/or HTML for the email body!");
        }
        public static void SendEmail(string fromEmailAddress, string fromFriendlyName, string toEmailAddress, string emailSubject, string emailBody)
        {

/*

            var client = new AmazonSimpleEmailServiceClient(Settings.Default.AWSAccessKey, 
                                                           Settings.Default.AWSSecretKey,
                                                            Amazon.RegionEndpoint.EUWest1);
            
            var client = new AmazonSimpleEmailServiceClient("AKIAIJINFUWK57TVYABQ",
                                                           "AosdbK3YfN8zvFltHNDuxFZrHVZNlLeBZQ1pGKG8dFCd",
                                                            Amazon.RegionEndpoint.EUWest1);
            */
            /*
            var destination = new Destination(new List<string>() {toEmailAddress});
            var subjectContent = new Content(subject);
            var bodyContent = new Content(body);
            var messageBody = new Body(bodyContent);
            var message = new Message(subjectContent, messageBody);

            var request = new SendEmailRequest(fromEmailAddress, destination, message);
           
            client.SendEmail(request);
            */

            String FROM = fromEmailAddress;  // Replace with your "From" address. This address must be verified.
             String TO = toEmailAddress; // Replace with a "To" address. If you have not yet requested
            // production access, this address must be verified.

            const String SUBJECT = "Amazon SES test (AWS SDK for .NET)";
            const String BODY = "This email was sent through Amazon SES by using the AWS SDK for .NET.";

            // Construct an object to contain the recipient address.
            Destination destination = new Destination();
            destination.ToAddresses = (new List<string>() { TO });

            // Create the subject and body of the message.
            Content subject = new Content(SUBJECT);
            Content textBody = new Content(BODY);
            Body body = new Body(textBody);

            // Create a message with the specified subject and body.
            Message message = new Message(subject, body);

            // Assemble the email.
            SendEmailRequest request = new SendEmailRequest(FROM, destination, message);

            // Choose the AWS region of the Amazon SES endpoint you want to connect to. Note that your production 
            // access status, sending limits, and Amazon SES identity-related settings are specific to a given 
            // AWS region, so be sure to select an AWS region in which you set up Amazon SES. Here, we are using 
            // the US East (N. Virginia) region. Examples of other regions that Amazon SES supports are USWest2 
            // and EUWest1. For a complete list, see http://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html 
            Amazon.RegionEndpoint REGION = Amazon.RegionEndpoint.EUWest1;

            // Instantiate an Amazon SES client, which will make the service call.
            var client = new AmazonSimpleEmailServiceClient(Settings.Default.AWSAccessKey,
                                                           Settings.Default.AWSSecretKey,
                                                            Amazon.RegionEndpoint.EUWest1);

            // Send the email.
          //  client.VerifyEmailAddress(new VerifyEmailAddressRequest() {EmailAddress = fromEmailAddress});


                client.SendEmail(request);
                Console.WriteLine("Email sent!");


        }
        public bool SendEmail()
        {
            //INITIALIZE AWS CLIENT//
            AmazonSimpleEmailServiceConfig amConfig = new AmazonSimpleEmailServiceConfig();
            //amConfig.UseSecureStringForAwsSecretKey = false;
            AmazonSimpleEmailServiceClient amzClient = new AmazonSimpleEmailServiceClient(
              AppSettingHelper.GetAmazonAccessKey(),AppSettingHelper.GetAmazonSecretKey(),//ConfigurationManager.AppSettings["AWSAccessKey"].ToString(),
               RegionEndpoint.USEast1);// ConfigurationManager.AppSettings["AWSSecretKey"].ToString(), amConfig);

            //ArrayList that holds To Emails. It can hold 1 Email to any
            //number of emails in case what to send same message to many users.
            var to = new List<string>();
            to.Add("*****@*****.**");

            //Create Your Bcc Addresses as well as Message Body and Subject
            Destination dest = new Destination();
            dest.BccAddresses.Add("*****@*****.**");
            //string body = Body;
            string subject = "Subject : " + "Demo Mail";
            Body bdy = new Body();
            bdy.Html = new Amazon.SimpleEmail.Model.Content("Test Mail");
            Amazon.SimpleEmail.Model.Content title = new Amazon.SimpleEmail.Model.Content(subject);
            Message message = new Message(title, bdy);

            //Create A Request to send Email to this ArrayList with this body and subject
            try
            {
                SendEmailRequest ser = new SendEmailRequest("*****@*****.**", dest, message);
                SendEmailResponse seResponse = amzClient.SendEmail(ser);
               // SendEmailResult seResult = seResponse.SendEmailResult;
            }
            catch (Exception ex)
            {

            }

            return true;
        }
        public override void SendMail(object sender, EmailToSendArgs e)
        {
            if (nextCanSend > DateTime.Now)
                System.Threading.Thread.Sleep(nextCanSend.Subtract(DateTime.Now));

            using (var ses = Amazon.AWSClientFactory.CreateAmazonSimpleEmailServiceClient(
                _configuration.Amazon.Key,
                _configuration.Amazon.Secret))
            {
                Destination destination = new Destination();
                destination.WithToAddresses(e.Message.To.ToStringArray());

                Content subject = new Content();
                subject.WithCharset("UTF-8");
                subject.WithData(e.Message.Subject);

                Body body = new Body();
                if (!string.IsNullOrWhiteSpace(e.Message.Html))
                {
                    Content html = new Content();
                    html.WithCharset("UTF-8");
                    html.WithData(e.Message.Html);
                    body.WithHtml(html);
                }

                if (!string.IsNullOrWhiteSpace(e.Message.Text))
                {
                    Content text = new Content();
                    text.WithCharset("UTF-8");
                    text.WithData(e.Message.Text);
                    body.WithText(text);
                }

                Message message = new Message();
                message.WithBody(body);
                message.WithSubject(subject);

                SendEmailRequest request = new SendEmailRequest();
                request.WithDestination(destination);
                request.WithMessage(message);
                request.WithSource(e.Message.From);

                try
                {
                    Console.WriteLine("sending email from {0}", e.Message.From);
                    SendEmailResponse response = ses.SendEmail(request);

                    SendEmailResult result = response.SendEmailResult;

                    logger.Debug("Email sent.");
                    logger.Debug(String.Format("Message ID: {0}",
                                               result.MessageId));

                    nextCanSend = _lastSend.AddSeconds(_maxSendRate);
                }
                catch (Exception ex)
                {
                    logger.Fatal("failed to send email", ex);

                    e.SendingFailed = true;
                }
            }
            base.SendMail(sender, e);
        }