Beispiel #1
0
        private async Task SendEmails(IServiceScope scope, CancellationToken stoppingToken)
        {
            MailQueueDbContext dbContext  = scope.ServiceProvider.GetRequiredService <MailQueueDbContext>();
            MailSender         mailSender = scope.ServiceProvider.GetRequiredService <MailSender>();

            Expression <Func <Mail, bool> > query = mail => mail.Error == null && !mail.Success;

            while (await dbContext.Mails.AnyAsync(query))
            {
                using IDbContextTransaction transaction = dbContext.Database.BeginTransaction();
                Mail mailToSend = await dbContext.Mails.FirstAsync(query);

                try
                {
                    await mailSender.SendEmail(mailToSend.Content, new EmailContext(mailToSend));

                    mailToSend.Success = true;
                    mailToSend.Sent    = DateTime.UtcNow;
                }
                catch (Exception e)
                {
                    mailToSend.Error = e.Message;
                }

                await dbContext.SaveChangesAsync();

                await transaction.CommitAsync();
            }
        }
Beispiel #2
0
        public async Task SendEmail <T>(string template, T context) where T : EmailContext
        {
            string content = await this.templateEngine.Render <T>(template, context);

            var newMail = new Mail
            {
                Id      = Guid.NewGuid(),
                To      = context.To?.Address ?? "",
                Subject = context.Subject,
                Content = content,
                Owner   = EnvironmentUtils.GetMachineIdentifier(),
            };

            await mailQueueDbContext.Mails.AddAsync(newMail);

            await mailQueueDbContext.SaveChangesAsync();
        }