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")); }
/// <inheritdoc /> public override async Task <Boolean> SendPasswordRecovery(IdAndCode request, ServerCallContext context) { var response = await m_emailSender .To(request.Email) .Subject("Spares Manual - Password Recovery") .UsingTemplateFromEmbedded("Email.Templates.PasswordRecovery.cshtml", new PasswordRecoveryModel { Url = $"https://localhost:5468/reset?usr={request.UserId}&token={HttpUtility.UrlEncode(request.Code)}" }, typeof(PasswordRecoveryModel).Assembly) .SendAsync(context.CancellationToken) .ConfigureAwait(false); return(new Boolean { Success = response.Successful }); }
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}."); } }
/// <inheritdoc /> public override async Task <Boolean> SendPasswordRecovery(EmailAndCode request, ServerCallContext context) { var response = await m_emailSender .To(request.Email) .Subject("Spares Manual - Password Recovery") .UsingTemplateFromEmbedded("Email.Templates.PasswordRecovery.cshtml", new PasswordRecoveryModel { Code = request.Code }, typeof(PasswordRecoveryModel).Assembly) .SendAsync(context.CancellationToken) .ConfigureAwait(false); return(new Boolean { Success = response.Successful }); }
public async Task <bool> SendAsync(EmailData emailData) { var sender = _fluentEmail .To(emailData.To) .Subject(emailData.Subject); if (!string.IsNullOrEmpty(emailData.Template)) { var tplNamespace = $"{_mailSettings.EmailTemplatesNamespace}.{emailData.Template}.cshtml"; sender.UsingTemplateFromEmbedded(tplNamespace, emailData.Model.ToExpando(), _mailSettings.EmailTemplatesDiscoveryType.Assembly); } else if (emailData.BodyDelegate != null) { sender.Body(emailData.BodyDelegate()); } else { sender.Body(emailData.Body); } var result = await sender.SendAsync(); if (result.Successful) { return(true); } _notificationContext.AddNotifications(result.ErrorMessages.ToArray()); return(false); }
public Task SendEmailWithTemplate() { return(_fluentEmail .To("") .Subject($"{""} just joined Skipper Agency") .UsingTemplateFromFile($"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}/EmailTemplates/NewSkipperNotice/NewSkipperNoticeTemplate.cshtml", "") .SendAsync()); }
public async Task SendEmailAsync(EmailMessage message, Object model, EmailTemplate template) { await _email .To(emailAddress : message.To) .Subject(subject: message.Subject) .UsingTemplateFromEmbedded(string.Format(TemplatePath, template), ToExpando(model), GetType().Assembly) .SendAsync(); }
public async Task SendConfirmationLinkEmail(string address, string fullname, string emailConfirmationLink) { var emailConfirmationTemplatePath = Path.Combine( Directory.GetCurrentDirectory(), "_Templates/Email/EmailConfirmation.html" ); var emailTemplate = File.ReadAllText(emailConfirmationTemplatePath); var email = emailTemplate .Replace("[%fullname%]", fullname) .Replace("[%url%]", emailConfirmationLink); await _emailSender .To(address) .Subject("Confirm your account email.") .Body(email, true) .SendAsync(); }
public async Task <IncidentBasePayload> AddIncidentAsync(AddIncidentInput input, [ScopedService] ApplicationDbContext context, [FromServices] IFluentEmail email, CancellationToken cancellationToken) { DateTime?endedAt = null; if (input.EndedAt.HasValue) { endedAt = input.EndedAt; } var incident = new Incident { Title = input.Title, Description = input.Description !, DescriptionHtml = MarkdownHelper.ToHtml(input.Description), Service = await context.Service.DeferredFirst(x => x.Id == input.ServiceId).FromCacheAsync(cancellationToken), StartedAt = input.StartedAt, EndedAt = endedAt, Author = await context.User.DeferredFirst(x => x.Id == Int32.Parse(_httpContextAccessor.HttpContext !.User.FindFirst(ClaimTypes.Name) !.Value)).FromCacheAsync(cancellationToken) }; await context.Incident.AddAsync(incident, cancellationToken); await context.SaveChangesAsync(cancellationToken); var template = await context.Settings.Where(x => x.Key == "backend.email.template.incident.create").DeferredFirst().FromCacheAsync(cancellationToken); var emailDomain = await context.Settings.Where(x => x.Key == "backend.email.domain").DeferredFirst().FromCacheAsync(cancellationToken); try { await context.Subscriber.ForEachAsync((subscriber) => { if (!template.Value.IsNullOrEmpty()) { email.To(subscriber.Email).Subject($"Incident Created: {incident.Service.Name}").UsingTemplate(template.Value, new { Title = incident.Title, Description = incident.Description, ServiceName = incident.Service.Name, StartedAd = incident.StartedAt.ToString(CultureInfo.InvariantCulture), EndedAt = incident.EndedAt?.ToString(CultureInfo.InvariantCulture), Attachements = incident.Files }); // We set the message ID so we can reference it in status updates and what not. email.Header("Message-ID", $"<{incident.Id}@{emailDomain.Value}>"); email.Send(); } }, cancellationToken); } catch (Exception e) { Console.WriteLine(e.Message); } QueryCacheManager.ExpireType <Incident>(); return(new IncidentBasePayload(incident)); }
public async Task SendEmail(string to, string name, string subject, string body) { var template = @$ "Dear @Model.Name, {body}"; var res = await _fluentEmail .To("*****@*****.**") .Subject("test email subject") .UsingTemplate(template, new { Name = name }).SendAsync(); await SaveNotification(body, subject, to, NotificationType.Email, res.Successful, null, new List <Guid>()); }
public async Task SendEmail(IFluentEmail email, ShoppingCart model, string mailTo) { var template = $"{Directory.GetCurrentDirectory()}/Views/Email/order_confirmation.cshtml"; await email .To(mailTo) .Subject("Order Confirmation") .UsingTemplateFromFile(template, model) .SendAsync(); var a = 23; }
public async Task <bool> SendInvitedNotification(string emailAddress, string username, string rawPassword, string firstName, string lastName) { var senderName = _configuration["Mail:Name"]; var email = _fluentEmail .To(emailAddress) .Subject("GDPR System - Invite Mail") .UsingTemplateFromEmbedded( "Web.Api.Infrastructure.EmailTemplate.InviteEmail.cshtml", new { Email = emailAddress, Username = username, FirstName = firstName, LastName = lastName, RawPassword = rawPassword, SenderName = senderName }, this.GetType().GetTypeInfo().Assembly); var response = await email.SendAsync(); return(response.Successful); }
public async Task <bool> SendDigitalRewardEmail(string to, string toName, string subject, DigitalRewardEmail emailProps, CancellationToken cancellationToken) { var template = "<p>Hi SSW Marketing</p><p>@Model.RecipientName has claimed @Model.RewardName.</p></p>Please generate a voucher code and send it to @Model.RecipientEmail.</p><p>Thanks,</p><p>SSW Rewards Notification Service</p>"; var result = await _fluentEmail .To(to) .Subject(subject) .UsingTemplate(template, emailProps) .SendAsync(cancellationToken); if (result.Successful) { return(true); } else { _logger.LogError("Error sending email", _fluentEmail); return(false); } }
public static async Task SendEmailVerification(this IFluentEmail email, string to, string verificationLink) { await email .To(to) .Subject("Please Verify your email Address") .UsingTemplateFile("VerifyEmail.cshtml", new VerifyEmailViewModel { VerificationLink = verificationLink }) .SendAsync(); }
public async Task <Result> SendWelcomeEmail(UserEdit user, string activateUrl) { var result = new Result(); var response = await _email .To(user.Email) .Subject("Welcome to One Advisor") .UsingTemplate(Welcome.Template, new { FirstName = user.FirstName.ToUpper(), UserName = user.UserName, ActivateUrl = activateUrl }) .SendAsync(); result.Success = response.Successful; if (!result.Success) { result.Errors = response.ErrorMessages; return(result); } return(result); }
public async Task Send <TData>(MailTemplateData mailData, Type template, TData data) { var mailTemplate = _serviceProvider.GetRequiredService(template); if (!(mailTemplate is IMailTemplate <TData>)) { throw new ArgumentException($"{template.FullName} debe implementar la interfaz {typeof(IMailTemplate<>).FullName}"); } (mailTemplate as IMailTemplate <TData>).Data = data; var templateName = mailTemplate.GetType().FullName ?? ""; templateName = templateName.Substring(0, templateName.Length - 5); var body = await _viewRenderer.Render(templateName, mailTemplate); await _email .To(mailData.Emails.Select(email => new Address(email)).ToList()) .Subject(mailData.Subject) .Body(body, isHtml: true) .SendAsync(); }
public Task Handle(ISendEmailEvent message) { return(Task.Run(() => { if (!string.IsNullOrWhiteSpace(message.From)) { _client = _client.SetFrom(message.From); } _client.To(message.To).Subject(message.Subject).UsingTemplateFromEmbedded( $"ManageYourBudget.EmailService.Views.{message.Type}.cshtml", message, _assembly).Send(); })); }
public static async Task SendForgotPasswordEmail(this IFluentEmail email, string to, string forgotPasswordLink) { var subject = "Forgot Password Confirmation"; await email .To(to) .Subject(subject) .UsingTemplateFile("ForgotPasswordEmail.cshtml", new ForgotPasswordEmailViewModel() { Subject = subject, ForgotPasswordLink = forgotPasswordLink }) .SendAsync(); }
private async Task SendConfirmationEmail(SendConfirmationEmailRequestDto sendConfirmationEmailRequest, User user, CancellationToken cancellationToken) { if ((DateTimeOffset.Now - user.ConfirmationEmailRequestedOn) < _appSettings.Value.IdentitySettings.ConfirmationEmailResendDelay) { throw new TooManyRequestsExceptions(nameof(ErrorStrings.WaitForConfirmationEmailResendDelay)); } var token = await _userManager.GenerateEmailConfirmationTokenAsync(user); var controller = RouteData.Values["controller"] !.ToString(); var confirmationLink = Url.Action(nameof(ConfirmEmail), controller, new { user.Email, token }, HttpContext.Request.Scheme); var assembly = typeof(Program).Assembly; var result = await _fluentEmail .To(user.Email, user.DisplayName) .Subject(EmailStrings.ConfirmationEmailSubject) .UsingTemplateFromEmbedded("TodoTemplate.Api.Resources.EmailConfirmation.cshtml", new EmailConfirmationModel { ConfirmationLink = confirmationLink, HostUri = new Uri($"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}{HttpContext.Request.PathBase}") }, assembly) .SendAsync(cancellationToken); user.ConfirmationEmailRequestedOn = DateTimeOffset.Now; await _userManager.UpdateAsync(user); if (!result.Successful) { throw new ResourceValidationException(result.ErrorMessages.ToArray()); } }
public async Task <IActionResult> ProcessSystemAccesses(List <int> systemAccessIds) { var identity = (ClaimsIdentity)User.Identity; int employeeId = Int32.Parse(identity.GetClaim("EmployeeId")); string employeeName = identity.GetClaim(ClaimTypes.Name); var systemAccesses = _systemService.GetSystemAccesses(systemAccessIds); foreach (var systemAccess in systemAccesses) { systemAccess.ProcessedById = employeeId; systemAccess.ProcessedOn = DateTime.Now; await _auditLog.Append(employeeId, LogActionType.Process, LogResourceType.SystemAccess, systemAccess.SystemAccessId, $"{employeeName} processed system access with id {systemAccess.SystemAccessId}"); } _systemService.SaveChanges(); var systemAccessesByRequest = systemAccesses.GroupBy(s => s.Request, s => s).ToDictionary(g => g.Key, g => g.ToList()); foreach (var request in systemAccessesByRequest.Keys) { string emailName = "RequestProcessed"; var model = new { _emailHelper.AppUrl, _emailHelper.AppEmail, Request = request, SystemAccesses = systemAccessesByRequest.GetValueOrDefault(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(); } return(RedirectToAction(nameof(MyProcessings))); }
public static async Task SendNewContactRequestEmail(this IFluentEmail email, List <Address> tosAddresses, ContactUsRequest request) { var subject = $"CSLabs - New contact request from {request.Email}"; await email .To(tosAddresses) .Subject(subject) //.AttachFromFilename(contactRequest.UserScreenshot)//possible image attachment .UsingTemplateFile("ContactRequest.cshtml", new ContactRequestViewModel { Body = request.Message, Email = request.Email, Subject = subject }) .SendAsync(); }
public async Task <bool> SendMessage(MailModel model) { try { var result = await _email .To(model.ToEmail) .Subject(model.Subject) .Body(model.Body) .SendAsync(); if (!result.Successful) { _logger.LogError("Failed to send an email.\n{Errors}", string.Join(Environment.NewLine, result.ErrorMessages)); } return(result.Successful); } catch (Exception ex) { _logger.LogError($"{DateTime.Now}: Failed to send email notification ❌! ({ex.Message})"); return(false); } }
public async Task <IActionResult> Index([FromServices] IFluentEmail email) { var model = new { Name = "test name" }; await email .To("*****@*****.**") .Subject("test email subject") .UsingTemplate(@"hi @Model.Name this is a razor template @(5 + 5)!", model) .SendAsync(); return(View()); }
private async Task SendEmailWithCallbackUrlAsync( string email, BaseEmailModel model, string subject, string view ) { await _smtpClient .To(email) .Subject(subject) .UsingTemplateFromEmbedded( view, model, GetType().GetTypeInfo().Assembly) .SendAsync(); }
public IActionResult Test() { string receipient = "*****@*****.**"; string emailName = "Test"; var model = new { _emailHelper.AppUrl, _emailHelper.AppEmail }; string subject = _emailHelper.GetSubjectFromTemplate(emailName, model, _email.Renderer); _email.To(receipient) .Subject(subject) .UsingTemplateFromFile(_emailHelper.GetBodyTemplateFile(emailName), model) .SendAsync(); ViewData["Receipient"] = receipient; ViewData["Subject"] = subject; return(View()); }
public void Notify(Notification notification, IEnumerable <User> users) { var userEmails = _notificationCrossDomainRepository .GetUsersConcernedByThisNotifier(NotifierType.Mail, users) .Where(user => !string.IsNullOrEmpty(user.Email)) .Select(user => new Address(user.Email)) .ToList(); if (userEmails.Any()) { _email .To(userEmails) .Subject(notification.Title) .Body(notification.Content) .Send(); } }
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(); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (ModelState.IsValid) { var user = new IdentityUser { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { userId = user.Id, code = code }, protocol: Request.Scheme); /* * await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", * $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); * * await _signInManager.SignInAsync(user, isPersistent: false); */ await _fluentEmail.To(Input.Email) .Subject("Test fluent email") .Body($"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.") .SendAsync(); return(LocalRedirect(returnUrl)); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }
private async Task SendEmail(DigestItem[] digestItems) { string body = $"<table>"; foreach (var result in digestItems) { if (result.Successful) { foreach (var account in result.Transactions.accounts) { var accountTransactions = result.Transactions.transactions.Where(p => p.account_id == account.account_id).ToList(); if (accountTransactions.Any()) { body += $"<tr><td colspan='3'><b>{result.InstitutionAccount.InstitutionNickName} - {account.official_name ?? account.name}</b></td></tr>"; foreach (var transaction in accountTransactions) { body += $"<tr style='color:{(transaction.pending ? "darkgray" : "black")};'>"; body += $"<td>{transaction.name}</td>"; body += $"<td style='text-align:right;padding-left:10px;'>{transaction.amount:c}</td>"; body += $"<td>{(transaction.pending ? "(pending)" : "")}</td>"; body += "</tr>"; } } } } else { body += $"<tr><td colspan='3'><b>{result.InstitutionAccount.InstitutionNickName}</b></td></tr>"; body += $"<tr><td colspan='3'>{result.Exception}</td></tr>"; } } body += $"</table>"; var response = await _email .To(Environment.GetEnvironmentVariable("report_email")) .Subject($"Daily Transaction Digest for {DateTime.Today.AddDays(-1).ToShortDateString()}") .Body(body, isHtml: true) .SendAsync(); if (!response.Successful) { throw new Exception("failed to send email: " + response.ErrorMessages[0]); } }
/// <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())); }
public void Initialize() { email = new MockEmail(); email.To(toEmail).Subject(subject).Body(body); }