Esempio n. 1
0
        public void SendEmail()
        {
            EmailClient client = CreateEmailClient();

            #region Snippet:Azure_Communication_Email_Send
            // Create the email content
            var emailContent = new EmailContent("This is the subject");
            emailContent.PlainText = "This is the body";

            // Create the recipient list
            var emailRecipients = new EmailRecipients(
                new List <EmailAddress>
            {
                new EmailAddress(
                    //@@ email: "<recipient email address>"
                    //@@ displayName: "<recipient displayname>"
                    /*@@*/ email: TestEnvironment.ToEmailAddress,
                    /*@@*/ displayName: "Customer Name")
            });

            // Create the EmailMessage
            var emailMessage = new EmailMessage(
                //@@ sender: "<Send email address>" // The email address of the domain registered with the Communication Services resource
                /*@@*/ sender: TestEnvironment.AzureManagedFromEmailAddress,
                emailContent,
                emailRecipients);

            SendEmailResult sendResult = client.Send(emailMessage);

            Console.WriteLine($"Email id: {sendResult.MessageId}");
            #endregion Snippet:Azure_Communication_Email_Send

            Assert.False(string.IsNullOrEmpty(sendResult.MessageId));
        }
        public SendEmailResponse DeepCloneWithSendEmailResult(SendEmailResult sendEmailResult)
        {
            var result = new SendEmailResponse(
                sendEmailResult,
                this.ExceptionToString?.DeepClone(),
                this.CommunicationLog?.DeepClone());

            return(result);
        }
Esempio n. 3
0
        public async Task SendEmailAsync()
        {
            EmailClient emailClient = CreateEmailClient();

            SendEmailResult response = await SendEmailAsync(emailClient);

            Assert.IsNotNull(response);
            Assert.IsFalse(string.IsNullOrWhiteSpace(response.MessageId));
            Console.WriteLine($"MessageId={response.MessageId}");
        }
Esempio n. 4
0
        /// <summary>
        /// Send email message
        /// </summary>
        /// <param name="emailAccount">Email account</param>
        /// <param name="messageTemplate">Message template</param>
        /// <param name="message">Message</param>
        /// <param name="emailCategory">Email category</param>
        /// <param name="emails">Emails</param>
        /// <param name="asynchronously">Whether send by asynchronously</param>
        /// <returns>Return send result</returns>
        public static async Task <SendMessageResult> SendEmailMessageAsync(EmailAccount emailAccount, MessageTemplate messageTemplate, MessageInfo message, string emailCategory, IEnumerable <string> emails, bool asynchronously = true)
        {
            var msgResult = GetEmailOptions(messageTemplate, message, emailCategory, emails, asynchronously, out var emailOptions);

            if (!msgResult.Success || emailOptions == null)
            {
                return(msgResult);
            }
            SendEmailResult emailSendResult = (await EmailManager.SendAsync(emailAccount, emailOptions).ConfigureAwait(false))?.FirstOrDefault();

            return((emailSendResult?.Success ?? false) ? SendMessageResult.SendSuccess() : SendMessageResult.SendFailed(emailSendResult?.Message));
        }
Esempio n. 5
0
        public async Task SendEmailWithAttachmentAsync()
        {
            EmailClient client = CreateEmailClient();

            var emailContent = new EmailContent("This is the subject");

            emailContent.PlainText = "This is the body";

            var emailRecipients = new EmailRecipients(
                new List <EmailAddress>
            {
                new EmailAddress(
                    //@@ email: "<recipient email address>"
                    //@@ displayName: "<recipient displayname>"
                    /*@@*/ email: TestEnvironment.ToEmailAddress,
                    /*@@*/ displayName: "Customer Name")
            });

            #region Snippet:Azure_Communication_Email_Send_With_AttachmentsAsync
            // Create the EmailMessage
            var emailMessage = new EmailMessage(
                //@@ sender: "<Send email address>" // The email address of the domain registered with the Communication Services resource
                /*@@*/ sender: TestEnvironment.AzureManagedFromEmailAddress,
                emailContent,
                emailRecipients);

#if SNIPPET
            var filePath       = "<path to your file>";
            var attachmentName = "<name of your attachment>"
                                 EmailAttachmentType attachmentType = EmailAttachmentType.Txt;
#endif

            // Convert the file content into a Base64 string
#if SNIPPET
            byte[] bytes = File.ReadAllBytes(filePath);
            string attachmentFileInBytes = Convert.ToBase64String(bytes);
#else
            string attachmentName = "Attachment.txt";
            EmailAttachmentType attachmentType = EmailAttachmentType.Txt;
            var attachmentFileInBytes          = "VGhpcyBpcyBhIHRlc3Q=";
#endif
            var emailAttachment = new EmailAttachment(attachmentName, attachmentType, attachmentFileInBytes);

            emailMessage.Attachments.Add(emailAttachment);

            SendEmailResult sendResult = await client.SendAsync(emailMessage);

            #endregion Snippet:Azure_Communication_Email_Send_With_AttachmentsAsync
        }
Esempio n. 6
0
        public void GetSendStatus()
        {
            EmailClient emailClient = CreateEmailClient();

            SendEmailResult response = SendEmail(emailClient);

            Assert.IsNotNull(response);
            Assert.IsFalse(string.IsNullOrWhiteSpace(response.MessageId));
            Console.WriteLine($"MessageId={response.MessageId}");

            SendStatusResult messageStatusResponse = emailClient.GetSendStatus(response.MessageId);

            Assert.IsNotNull(messageStatusResponse);
            Console.WriteLine(messageStatusResponse.Status);
        }
Esempio n. 7
0
        public ActionResult Index(EmailContentViewModel model)
        {
            var result = new SendEmailResult();

            try
            {
                _emailService.Send(model);

                result.Result = "Email sent!";
            }
            catch (Exception e)
            {
                result.Result = $"Email failed to send: {e.Message}";
            }

            TempData["result"] = result;

            return(RedirectToAction("EmailResult"));
        }
Esempio n. 8
0
        public async Task <IActionResult> OnPostAsync()
        {
            var user = await _userService.FindByEmailAsync(Input.Email);

            if (user == null)
            {
                _logger.LogInformation("User not found", null);
                // Don't reveal that the user does not exist or is not confirmed
                return(RedirectToPage("./ForgotPasswordConfirmation"));
            }

            if (!(await _userService.IsEmailConfirmedAsync(user)))
            {
                _logger.LogInformation("user exists, confirm email is sent but user has not yet confirmed so cannot reset password.", null);
                return(RedirectToPage("./ForgotPasswordConfirmation"));
            }

            // For more information on how to enable account confirmation and password reset please
            // visit https://go.microsoft.com/fwlink/?LinkID=532713
            var code = await _userService.GeneratePasswordResetTokenAsync(user);

            code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
            var callbackUrl = Url.Page(
                "/Account/ResetPassword",
                pageHandler: null,
                values: new { area = "Identity", code },
                protocol: Request.Scheme);

            SendEmailResult sendMailRslt = await _sendEmailService.SendEmailAsync(
                user.UserName,
                Input.Email,
                $"{await TranslationsService.TranslateAsync("Reset password")}",
                $"{await TranslationsService.TranslateAsync("Klik")} <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>{await TranslationsService.TranslateAsync("hier")}</a> {await TranslationsService.TranslateAsync("om uw wachtwoord te resetten.")}");

            if (!sendMailRslt.Success)
            {
                _logger.LogWarning(sendMailRslt.Message, null);
            }


            return(RedirectToPage("./ForgotPasswordConfirmation"));
        }
Esempio n. 9
0
        public SendEmailResponse(
            SendEmailResult sendEmailResult,
            string exceptionToString = null,
            string communicationLog  = null)
        {
            new { sendEmailResult }.AsArg().Must().NotBeEqualTo(SendEmailResult.Unknown);

            if (sendEmailResult != SendEmailResult.Success)
            {
                new { exceptionToString }.AsArg().Must().NotBeNullNorWhiteSpace(Invariant($"When {nameof(sendEmailResult)} indicates a failure, {nameof(exceptionToString)} must not be null nor white space."));
            }

            if (sendEmailResult == SendEmailResult.Success)
            {
                new { exceptionToString }.AsArg().Must().BeNull(Invariant($"When {nameof(sendEmailResult)} indicates success, {nameof(exceptionToString)} must be null."));
            }

            this.SendEmailResult   = sendEmailResult;
            this.ExceptionToString = exceptionToString;
            this.CommunicationLog  = communicationLog;
        }
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = await _userService.FindByEmailAsync(Input.Email);

            if (user == null)
            {
                return(Page());
            }

            var userId = await _userService.GetUserIdAsync(user);

            var code = await _userService.GenerateEmailConfirmationTokenAsync(user);

            code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
            var callbackUrl = Url.Page(
                "/Account/ConfirmEmail",
                pageHandler: null,
                values: new { userId, code },
                protocol: Request.Scheme);
            SendEmailResult result = await _sendMailService.SendEmailAsync(
                user.UserName,
                Input.Email,
                $"{await TranslationsService.TranslateAsync("Confirm your email")}",
                $"{await TranslationsService.TranslateAsync("Klik")} <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>{await TranslationsService.TranslateAsync("hier")}</a> {await TranslationsService.TranslateAsync("pour confirmer votre compte.")}");

            if (!result.Success)
            {
                _logger.LogWarning(result.Message, null);
            }

            return(RedirectToPage("/Index"));
        }
Esempio n. 11
0
        /// <inheritdoc/>
        public async Task <SendEmailResult> SendEmailAsync(string templateName, EmailModel model)
        {
            bool            sent        = false;
            SendEmailResult emailResult = SendEmailResult.FailedResult;
            string          message     = string.Empty;

            try
            {
                message = await this.emailRenderer.RenderToStringAsync(templateName, model);

                SmtpClient client = new SmtpClient(this.smtpOptions.Host);
                client.UseDefaultCredentials = false;
                client.Credentials           = new NetworkCredential(this.smtpOptions.Username, this.smtpOptions.Password);
                client.Port      = this.smtpOptions.Port;
                client.EnableSsl = this.smtpOptions.UseSSL;

                MailMessage mailMessage = new MailMessage();
                mailMessage.From = new MailAddress(this.smtpOptions.EmailAddress, this.smtpOptions.Name);
                mailMessage.To.Add(model.Email);
                mailMessage.Body         = message;
                mailMessage.IsBodyHtml   = true;
                mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
                mailMessage.Subject      = model.Subject;
                client.Send(mailMessage);

                emailResult = SendEmailResult.SuccessResult;
                sent        = true;
            }
            catch (Exception ex)
            {
                await this.logger.LogErrorAsync(ex);
            }

            await this.logger.LogEmailAsync(model.Email, model.Name, model.Subject, message, sent);

            return(emailResult);
        }
Esempio n. 12
0
        private void SMTPSendCompleted(object sender, AsyncCompletedEventArgs e)
        {
            SendEmailResult result = new SendEmailResult();

            if (e.Cancelled)
            {
                result.id  = -1;
                result.msg = "已取消发送邮件";
            }
            else if (e.Error != null)
            {
                result.id  = 0;
                result.msg = "发送失败:" + e.Error.Message;
            }
            else
            {
                result.id  = (int)e.UserState;
                result.msg = "发送成功";
                CommandExceptionLog m = base.GetModel(result.id);
                if (m != null)
                {
                    //更新数据库 发送字段
                    m.IsSend = 1;
                    if (base.Update(m, "IsSend"))
                    {
                        log4net.LogHelper.WriteInfo(this.GetType(), "发送成功并且更新数据库成功" + result.id);//记录发送结果
                    }
                    else
                    {
                        log4net.LogHelper.WriteInfo(this.GetType(), "发送成功但是更新数据库失败" + result.id);//记录发送结果
                    }
                }
            }


            log4net.LogHelper.WriteInfo(this.GetType(), result.id + "==" + result.msg);//记录发送结果
        }
Esempio n. 13
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)
            {
                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);
                }


                try
                {
                    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);
                }
            }


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


            return(false);
        }
 /// <inheritdoc />
 public EmailMessage()
 {
     Result = new SendEmailResult();
 }
Esempio n. 15
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!");
        }
Esempio n. 16
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);
        }