예제 #1
0
        private async Task <SendResponse> sendEmail(IFluentEmail email, ClientConfiguration clientConfig)
        {
            var option = new SmtpClientOptions();

            if (!string.IsNullOrEmpty(this.config["Email:DevMode"]) && this.config["Email:DevMode"] == "true")
            {
                option.Server   = "localhost";
                option.User     = "";
                option.Password = "";
                option.Port     = 25;
                option.RequiresAuthentication = false;
                option.UseSsl = false;
            }
            else
            {
                option.Server   = clientConfig.Server;
                option.User     = clientConfig.EmailUserName;
                option.Password = clientConfig.EmailPassword;
                option.Port     = clientConfig.Port;
                option.RequiresAuthentication = clientConfig.RequiresAuthentication;
                option.UseSsl = clientConfig.UseSsl;
            }

            email.Sender = new MailKitSender(option);

            var status = await email.SendAsync();

            return(status);
        }
예제 #2
0
        public async Task SendEmailAsync(MailAddressCollection to, string subject, string htmlBody, IEnumerable <Attachment> attachments = null, CancellationToken cancellationToken = default)
        {
            var message = _email
                          .To(to.ToFluentEmailAddresses())
                          .SetFrom(_options.FromAddress, _options.FromName)
                          .Subject(subject)
                          .Body(htmlBody, true);

            if (attachments != null && attachments.Any())
            {
                message.Attach(attachments.ToFluentEmailAttachments().ToList());
            }

            try
            {
                var response = await _email.SendAsync(cancellationToken);

                if (!response.Successful)
                {
                    _logger.LogError($"Failed to send email to {to}. Email sender response:");
                    foreach (var errorMessage in response.ErrorMessages)
                    {
                        _logger.LogError(errorMessage);
                    }
                }
            }
            catch (Exception ex) {
                _logger.LogError(ex, $"Failed to send email to {to}.");
            }
        }
예제 #3
0
        public async Task <IActionResult> SubmitRequest(int id)
        {
            var request    = _requestService.GetRequest(id);
            var authResult = await _authService.AuthorizeAsync(User, request, "CanEditRequest");

            if (!authResult.Succeeded)
            {
                return(new ForbidResult());
            }

            request.RequestStatus = RequestStatus.UnderReview;
            request.SubmittedOn   = DateTime.Now;
            _requestService.SaveChanges();

            var identity = (ClaimsIdentity)User.Identity;
            await _auditLog.Append(identity.GetClaimAsInt("EmployeeId"), LogActionType.Submit, LogResourceType.Request, id,
                                   $"{identity.GetClaim(ClaimTypes.Name)} submitted request with id {id}");

            if (request.Reviews.Count > 0)
            {
                Employee reviewer   = request.OrderedReviews[0].Reviewer;
                string   receipient = reviewer.Email;
                string   emailName  = "ReviewRequest";
                var      model      = new { _emailHelper.AppUrl, _emailHelper.AppEmail, Request = request };
                string   subject    = _emailHelper.GetSubjectFromTemplate(emailName, model, _email.Renderer);
                await _email.To(receipient)
                .Subject(subject)
                .UsingTemplateFromFile(_emailHelper.GetBodyTemplateFile(emailName), model)
                .SendAsync();
            }
            else
            {
                request.RequestStatus = RequestStatus.Approved;
                request.CompletedOn   = DateTime.Now;
                _requestService.SaveChanges();

                foreach (var requestedSystem in request.Systems)
                {
                    var systemAccess = new SystemAccess(request, requestedSystem);
                    _systemService.AddSystemAccess(systemAccess);
                }

                string emailName = "ProcessRequest";
                var    model     = new { _emailHelper.AppUrl, _emailHelper.AppEmail, Request = request };
                _email.Subject(_emailHelper.GetSubjectFromTemplate(emailName, model, _email.Renderer))
                .UsingTemplateFromFile(_emailHelper.GetBodyTemplateFile(emailName), model);
                _email.Data.ToAddresses.Clear();
                var supportUnitIds = request.Systems.GroupBy(s => s.System.SupportUnitId, s => s).Select(g => g.Key).ToList();
                foreach (var supportUnitId in supportUnitIds)
                {
                    var supportUnit = _organizationService.GetSupportUnit((int)supportUnitId);
                    _email.To(supportUnit.Email);
                }
                await _email.SendAsync();
            }

            return(RedirectToAction("MyRequests"));
        }
예제 #4
0
        public void SendAsync_Method_Can_Be_Overridden()
        {
            Assert.AreEqual(email.Message.Body, body);
            Assert.AreEqual(email.Message.Subject, subject);

            email.SendAsync(MailDeliveryComplete);
            email.Cancel();

            Assert.AreEqual(email.Message.Body, "The SendAsync() method has been overridden");
        }
예제 #5
0
        public async Task SendFeedsAsync(string email, IEnumerable <RssFeedEmailModel> feeds)
        {
            // var configuration =
            var file = @$ "{Directory.GetCurrentDirectory()}\EmailTemplates\Index.cshtml";

            fluentEmail.Subject("Zestaw newsów");
            fluentEmail.To(email);
            fluentEmail.UsingTemplateFromFile(file, feeds, true);
            await fluentEmail.SendAsync();

            //.From("*****@*****.**")
            //.To(email)
            //.Subject("Zestaw newsów");
            //.UsingTemplateFromFile($"{Directory.GetCurrentDirectory()}/EmailTemplates/Index.cshtml", feeds, true);

            //   await configuration.SendAsync();
        }
예제 #6
0
        public async Task <SendResponse> Send(string toEmail, string toName, string givePresentTo)
        {
            var sender = new MailgunSender(
                _options.Domain, // Mailgun Domain
                _options.APIKey, // Mailgun API Key
                MailGunRegion.EU
                );

            Email.DefaultSender   = sender;
            Email.DefaultRenderer = new RazorRenderer();
            string subject = $"Your secret santa selection";

            IFluentEmail email = null;

            try
            {
                email = Email
                        .From("*****@*****.**")
                        .To(toEmail, toName)
                        .Subject(subject)
                        .UsingTemplateFromFile($"{Directory.GetCurrentDirectory()}/EmailTemplate.cshtml", new { Name = givePresentTo, GifterName = toName });
            }
            catch (TemplateCompilationException tex)
            {
                string body = $"your secret santa present is for {givePresentTo}";

                email = Email
                        .From("*****@*****.**")
                        .To(toEmail, toName)
                        .Subject(subject)
                        .UsingTemplateEngine(new ReplaceRenderer())
                        .Body(string.Format("Hello {0}, <br /> {1} ", toName, body));
                string x = tex.Message;
            }
            catch (Exception ex)
            {
                var x = ex.Message;
            }

            var response = await email.SendAsync();

            return(response);
        }
        /// <inheritdoc/>
        public async Task <SendResponse> SendEmailAsync(EmailMessage message)
        {
            message.ThrowIfNull(nameof(message));

            IFluentEmail email = fluentEmail
                                 .SetFrom(message.From.Address, message.From.DisplayName)
                                 .Subject(message.Subject)
                                 .Body(message.Message);

            message.To?.ForEach(to => email.To(to));
            message.Сс?.ForEach(cc => email.CC(cc));

            email.Data.IsHtml = true;

            logger.LogInformation($"Sending email with title \"{message.Subject}\" asynchronously");

            return(await Policy
                   .Handle <Exception>()
                   .WaitAndRetryForeverAsync(GetSleepTimeForRetry, LogRetryException)
                   .ExecuteAsync(() => email.SendAsync()));
        }
예제 #8
0
 private async Task SendAsync(IFluentEmail fluentEmail)
 => await fluentEmail.SendAsync();
예제 #9
0
        public async Task <IActionResult> Approve(int id, string password, string comments)
        {
            string username = ((ClaimsIdentity)User.Identity).GetClaim(ClaimTypes.NameIdentifier);

            if (!_adService.Authenticate(username, password))
            {
                RedirectToAction(nameof(EditReview), new { id });
            }

            Review review     = _requestService.GetReview(id);
            var    authResult = await _authService.AuthorizeAsync(User, review, "CanEnterReview");

            if (!authResult.Succeeded)
            {
                return(new ForbidResult());
            }

            Request request = _requestService.GetRequest(review.RequestId);

            review.Approve(comments);
            request.UpdatedOn = DateTime.Now;
            _requestService.SaveChanges();

            var identity = (ClaimsIdentity)User.Identity;
            await _auditLog.Append(identity.GetClaimAsInt("EmployeeId"), LogActionType.Approve, LogResourceType.Request, request.RequestId,
                                   $"{identity.GetClaim(ClaimTypes.Name)} approved request with id {request.RequestId}");

            if (review.ReviewOrder < request.Reviews.Count - 1)
            {
                Review nextReview = request.OrderedReviews[review.ReviewOrder + 1];
                string emailName  = "ReviewRequest";
                var    model      = new { _emailHelper.AppUrl, _emailHelper.AppEmail, Request = request };
                string subject    = _emailHelper.GetSubjectFromTemplate(emailName, model, _email.Renderer);
                string receipient = nextReview.Reviewer.Email;
                _email.To(receipient)
                .Subject(subject)
                .UsingTemplateFromFile(_emailHelper.GetBodyTemplateFile(emailName), model)
                .Send();

                emailName  = "RequestUpdated";
                subject    = _emailHelper.GetSubjectFromTemplate(emailName, model, _email.Renderer);
                receipient = request.RequestedBy.Email;
                _email.To(receipient)
                .Subject(subject)
                .UsingTemplateFromFile(_emailHelper.GetBodyTemplateFile(emailName), model)
                .Send();
            }
            else // last review
            {
                request.RequestStatus = RequestStatus.Approved;
                request.CompletedOn   = DateTime.Now;
                _requestService.SaveChanges();

                foreach (var requestedSystem in request.Systems)
                {
                    var systemAccess = new SystemAccess(request, requestedSystem);
                    _systemService.AddSystemAccess(systemAccess);
                }

                string emailName  = "RequestApproved";
                var    model      = new { _emailHelper.AppUrl, _emailHelper.AppEmail, Request = request };
                string subject    = _emailHelper.GetSubjectFromTemplate(emailName, model, _email.Renderer);
                string receipient = request.RequestedBy.Email;
                _email.To(receipient)
                .Subject(subject)
                .UsingTemplateFromFile(_emailHelper.GetBodyTemplateFile(emailName), model)
                .Send();

                emailName = "ProcessRequest";
                _email.Subject(_emailHelper.GetSubjectFromTemplate(emailName, model, _email.Renderer))
                .UsingTemplateFromFile(_emailHelper.GetBodyTemplateFile(emailName), model);
                _email.Data.ToAddresses.Clear();
                var supportUnitIds = request.Systems.GroupBy(s => s.System.SupportUnitId, s => s).Select(g => g.Key).ToList();
                foreach (var supportUnitId in supportUnitIds)
                {
                    var supportUnit = _organizationService.GetSupportUnit((int)supportUnitId);
                    _email.To(supportUnit.Email);
                }
                await _email.SendAsync();
            }

            return(RedirectToAction(nameof(MyReviews)));
        }