Ejemplo n.º 1
0
        public async Task SendDownloadTokenAsync(Guid tokenId)
        {
            // Parse template with data
            var    tokenContract = query.Get <TokenEntity>().Where(x => x.Active && x.Id == tokenId).SelectTokenContract().Single();
            string downloadMail  = await _templateRepository.RenderTemplateAsync <DownloadMailModel>(TemplateConsts.MailDownload, new DownloadMailModel
            {
                BaseUrl = BaseUrl,
                Token   = tokenContract,
            });

            await _mailSender.SendAsync(tokenContract.CustomerEmail, Localization.Resource.MailSubject_DownloadToken, downloadMail);
        }
        public async Task <Registration> RegisterAsync(RegistrationType registrationType, string email = null, string password = null, string confirm = null, string firstName = null,
                                                       string lastName = null, DateTime?birthDt = null, Gender?gender = null, Role role = Role.User)
        {
            ValidateData(email, firstName, lastName, birthDt);

            Registration registration = new Registration
            {
                CreateDt = DateTimeOffset.Now,
                Guid     = Guid.NewGuid(),
                Status   = RegistrationStatus.Pending,
                Type     = registrationType
            };

            if (registrationType == RegistrationType.Email)
            {
                ValidatePassword(password, confirm);
                User user = new User
                {
                    FirstName    = firstName,
                    LastName     = lastName,
                    Role         = role,
                    Gender       = gender,
                    Registration = registration,
                    Status       = UserStatus.Pending,
                    Email        = email,
                };
                _passwordSetter.SetPassword(user, password, confirm);
                _unitOfWork.GetUserRepository().Insert(user);
                string emailBody = MailTemplates.Confirmation.Replace("[Confirmation_Link]", _currentHost + "registration/confirm?guid=" + registration.Guid);
                await _mailSender.SendAsync(new Letter { Topic = "Registration confirmation", Email = new string[] { user.Email }, Body = emailBody });
            }

            if (registrationType == RegistrationType.Google)
            {
                User user = new User
                {
                    FirstName    = firstName,
                    LastName     = lastName,
                    Role         = Role.User,
                    Gender       = gender,
                    Registration = registration,
                    Status       = UserStatus.Active,
                    Email        = email,
                };
                registration.Status = RegistrationStatus.Accepted;
                _unitOfWork.GetUserRepository().Insert(user);
                string emailBody = MailTemplates.Confirmation.Replace("[Confirmation_Link]", _currentHost + "registration/confirm?guid=" + registration.Guid);
                await _mailSender.SendAsync(new Letter { Topic = "Registration confirmation", Email = new string[] { user.Email }, Body = emailBody });
            }

            return(registration);
        }
Ejemplo n.º 3
0
        /// <summary>
        ///     Sends your messageBase asynchronously.  This method does not block.  If you need to know
        ///     when the messageBase has been sent, then override the OnMailSent method in MailerBase which
        ///     will not fire until the asyonchronous send operation is complete.
        /// </summary>
        public async Task <MailAttributes> DeliverAsync()
        {
            var deliverTask = _sender.SendAsync(MailAttributes);
            await deliverTask.ContinueWith(t => AsyncSendCompleted(MailAttributes));

            return(MailAttributes);
        }
Ejemplo n.º 4
0
        public async Task Handle(ShareListRequest message)
        {
            ValidateEmails(message.Emails);
            var userName = gaverContext.Users.Where(u => u.Id == message.UserId).Select(u => u.Name).Single();
            var request  = httpContextAccessor.HttpContext.Request;

            var mailTasks = new List <Task>();

            foreach (var email in message.Emails)
            {
                var token = new InvitationToken {
                    WishListId = message.WishListId
                };
                gaverContext.InvitationTokens.Add(token);

                var url  = Url.Combine(request.Scheme + "://" + request.Host, "list", message.WishListId.ToString(), "?token=" + token.Id.ToString());
                var mail = new MailModel {
                    To      = new[] { email },
                    From    = "*****@*****.**",
                    Subject = $"{userName} har delt en ønskeliste med deg",
                    Content = $@"<h1>{userName} har delt en ønskeliste med deg!</h1>
                <p><a href='{url}'>Klikk her for å se listen.</a></p>"
                };
                mailTasks.Add(mailSender.SendAsync(mail));
            }

            await gaverContext.SaveChangesAsync();

            await Task.WhenAll(mailTasks);
        }
Ejemplo n.º 5
0
        private async Task SendMailMessageAsync(string xmlFilePath, string logFilePath, string clientId)
        {
            var senderConfig = _senderConfigManager.Get();

            try
            {
                await _mailSender.SendAsync(senderConfig.Host, senderConfig.Port,
                                            new[] { senderConfig.SenderLogin, senderConfig.SenderPassword },
                                            senderConfig.To, "Converter error", "Client ID : " + clientId,
                                            new[] { xmlFilePath, logFilePath });
            }
            catch (MailSenderConfigurationException ex)
            {
                _log.Info(ex.Message);
                _log.Error(ex.ToString());
            }
            catch (MailAttachmentException ex)
            {
                _log.Info(ex.Message);
                _log.Error(ex.ToString());
            }
            catch (MailSenderException ex)
            {
                _log.Info(ex.Message);
                _log.Error(ex.ToString());
            }
        }
Ejemplo n.º 6
0
        public async Task NotifyUsersAsync(User user, string content)
        {
            if (_userValidator.ValidateUser(user))
            {
                await _mailSender.SendAsync(user.Email, content);
            }

            throw new InvalidOperationException();
        }
        protected override async Task <JobResult> ProcessQueueEntryAsync(QueueEntryContext <MailMessage> context)
        {
            _logger.LogTrace("Processing message {Id}.", context.QueueEntry.Id);

            try {
                await _mailSender.SendAsync(context.QueueEntry.Value).AnyContext();

                _logger.LogInformation("Sent message: to={To} subject={Subject}", context.QueueEntry.Value.To, context.QueueEntry.Value.Subject);
            } catch (Exception ex) {
                return(JobResult.FromException(ex));
            }

            return(JobResult.Success);
        }
Ejemplo n.º 8
0
        protected override async Task <JobResult> ProcessQueueEntryAsync(JobQueueEntryContext <MailMessage> context)
        {
            Logger.Trace().Message("Processing message '{0}'.", context.QueueEntry.Id).Write();

            try {
                await _mailSender.SendAsync(context.QueueEntry.Value).AnyContext();

                Logger.Info().Message("Sent message: to={0} subject=\"{1}\"", context.QueueEntry.Value.To, context.QueueEntry.Value.Subject).Write();
            } catch (Exception ex) {
                return(JobResult.FromException(ex));
            }

            return(JobResult.Success);
        }
        public async Task ChangeEmailAsync(User user, string email)
        {
            //Юзеры зареганные чз гугл не могут поменять почту
            if (user.Registration.Type == RegistrationType.Google)
            {
                throw new ActionCannotBeExecutedException(ExceptionMessages.ForbiddenToChangeEmail);
            }

            await _emailValidator.ValidateToRegistrationAsync(email);

            string emailBody = MailTemplates.Changing;
            await _mailSender.SendAsync(new Letter { Body = emailBody, Email = new string[] { email }, Topic = "Successful email change" });

            user.Email = email;
        }
Ejemplo n.º 10
0
        private Task SendCodeAsync(string email, Guid tokenId, string code)
        {
            const string subject = "Password reset";
            var          emails  = new[] { email };
            var          uri     = string.Format(_settings.ResetUriPattern, tokenId, code);
            var          message = $"Click <a href='{uri}'>here</a> for reset password.";

            try
            {
                return(_mailSender.SendAsync(_settings.FromName, _settings.FromAddress, subject, emails, true, message));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);

                return(Task.CompletedTask);
            }
        }
Ejemplo n.º 11
0
        protected override async Task <JobResult> ProcessQueueEntryAsync(QueueEntryContext <MailMessage> context)
        {
            _logger.Trace("Processing message '{0}'.", context.QueueEntry.Id);

            try {
                await _mailSender.SendAsync(context.QueueEntry.Value).ConfigureAwait(false);

                _logger.Info()
                .Message(() => $"Sent message: to={context.QueueEntry.Value.To.ToDelimitedString()} subject=\"{context.QueueEntry.Value.Subject}\"")
                .Write();
            } catch (Exception ex) {
                await context.QueueEntry.AbandonAsync().AnyContext();

                return(JobResult.FromException(ex));
            }

            return(JobResult.Success);
        }
        protected async override Task <JobResult> RunInternalAsync()
        {
            Log.Info().Message("Process email message job starting").Write();
            int totalEmailsProcessed = 0;
            int totalEmailsToProcess = Context.GetWorkItemLimit();

            while (!CancelPending && (totalEmailsToProcess == -1 || totalEmailsProcessed < totalEmailsToProcess))
            {
                QueueEntry <MailMessage> queueEntry = null;
                try {
                    queueEntry = await _queue.DequeueAsync();
                } catch (Exception ex) {
                    if (!(ex is TimeoutException))
                    {
                        Log.Error().Exception(ex).Message("An error occurred while trying to dequeue the next MailMessageNotification: {0}", ex.Message).Write();
                        return(JobResult.FromException(ex));
                    }
                }
                if (queueEntry == null)
                {
                    continue;
                }

                _statsClient.Counter(StatNames.EmailsDequeued);

                Log.Info().Message("Processing MailMessageNotification '{0}'.", queueEntry.Id).Write();

                try {
                    await _mailSender.SendAsync(queueEntry.Value);

                    totalEmailsProcessed++;
                    _statsClient.Counter(StatNames.EmailsSent);
                } catch (Exception ex) {
                    _statsClient.Counter(StatNames.EmailsSendErrors);
                    queueEntry.AbandonAsync().Wait();

                    Log.Error().Exception(ex).Message("Error sending message '{0}': {1}", queueEntry.Id, ex.Message).Write();
                }

                await queueEntry.CompleteAsync();
            }

            return(JobResult.Success);
        }
Ejemplo n.º 13
0
        protected async override Task <JobResult> RunInternalAsync(CancellationToken token)
        {
            QueueEntry <MailMessage> queueEntry = null;

            try {
                queueEntry = _queue.Dequeue();
            } catch (Exception ex) {
                if (!(ex is TimeoutException))
                {
                    Log.Error().Exception(ex).Message("Error trying to dequeue message: {0}", ex.Message).Write();
                    return(JobResult.FromException(ex));
                }
            }

            if (queueEntry == null)
            {
                return(JobResult.Success);
            }

            await _metricsClient.CounterAsync(MetricNames.EmailsDequeued);

            Log.Trace().Message("Processing message '{0}'.", queueEntry.Id).Write();

            try {
                await _mailSender.SendAsync(queueEntry.Value);

                await _metricsClient.CounterAsync(MetricNames.EmailsSent);

                Log.Info().Message("Sent message: to={0} subject=\"{1}\"", queueEntry.Value.To, queueEntry.Value.Subject).Write();
            } catch (Exception ex) {
                // TODO: Change to async once vnext is released.
                _metricsClient.Counter(MetricNames.EmailsSendErrors);
                Log.Error().Exception(ex).Message("Error sending message: id={0} error={1}", queueEntry.Id, ex.Message).Write();

                queueEntry.Abandon();
            }

            queueEntry.Complete();

            return(JobResult.Success);
        }
Ejemplo n.º 14
0
        private async Task SendEmail(string collectionName, User createdBy)
        {
            if (string.IsNullOrEmpty(createdBy.Email))
            {
                return;
            }

            var subject = $"New collection '{collectionName}' created";
            var newCollectionEmailBody =
                $"Dear {createdBy.FirstName},\n"
                + "\n"
                + $"You have just created a new collection '{collectionName}'. Please describe your data type in the data dictionary so others can understand and reuse your data type.\n"
                + "The data dictionary is part of the Wiki and is located here: http://wiki/Data_Dictionary \n"
                + "If you do not have a login already, you first have to register a new user. You will be able to edit the Wiki immediately after.\n"
                + "\n"
                + "If you have any questions please contact <some person or department>. Thank you for contributing to and enriching our data platform.\n"
                + "Best regards,\n"
                + "\t<some person or department>";

            await mailSender.SendAsync(createdBy.Email, subject, newCollectionEmailBody);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Sends a specified e-mail message.
        /// </summary>
        public async Task SendMailAsync(MailMessageDTO message)
        {
            if (From != null)
            {
                message.From = From;
            }
            if (!string.IsNullOrEmpty(SubjectFormatString))
            {
                message.Subject = string.Format(SubjectFormatString, message.Subject);
            }
            if (!string.IsNullOrEmpty(BodyTextFormatString) && !string.IsNullOrEmpty(message.BodyText))
            {
                message.BodyText = string.Format(BodyTextFormatString, message.BodyText);
            }
            if (!string.IsNullOrEmpty(BodyHtmlFormatString) && !string.IsNullOrEmpty(message.BodyHtml))
            {
                message.BodyHtml = string.Format(BodyHtmlFormatString, message.BodyHtml);
            }

            if (OverrideToAddresses != null && OverrideToAddresses.Any())
            {
                message.To.Clear();
                message.Cc.Clear();
                message.Bcc.Clear();

                foreach (var address in OverrideToAddresses)
                {
                    message.To.Add(address);
                }
            }

            var sendingArgs = new MessageSendingEventArgs(message);

            OnMessageSending(sendingArgs);

            if (!sendingArgs.Cancel)
            {
                await sender.SendAsync(sendingArgs.Message);
            }
        }
Ejemplo n.º 16
0
        protected async override Task <JobResult> RunInternalAsync(CancellationToken token)
        {
            Log.Info().Message("Process email message job starting").Write();

            QueueEntry <MailMessage> queueEntry = null;

            try {
                queueEntry = _queue.Dequeue();
            } catch (Exception ex) {
                if (!(ex is TimeoutException))
                {
                    Log.Error().Exception(ex).Message("An error occurred while trying to dequeue the next MailMessageNotification: {0}", ex.Message).Write();
                    return(JobResult.FromException(ex));
                }
            }
            if (queueEntry == null)
            {
                return(JobResult.Success);
            }

            _statsClient.Counter(StatNames.EmailsDequeued);

            Log.Info().Message("Processing MailMessageNotification '{0}'.", queueEntry.Id).Write();

            try {
                await _mailSender.SendAsync(queueEntry.Value);

                _statsClient.Counter(StatNames.EmailsSent);
            } catch (Exception ex) {
                _statsClient.Counter(StatNames.EmailsSendErrors);
                queueEntry.Abandon();

                Log.Error().Exception(ex).Message("Error sending message '{0}': {1}", queueEntry.Id, ex.Message).Write();
            }

            queueEntry.Complete();

            return(JobResult.Success);
        }
Ejemplo n.º 17
0
 public virtual Task <IEmailOutput> Send(IMailActionInputModel mailActionInputModel)
 {
     try
     {
         return(_mailSender.SendAsync(new MailInput
         {
             To = mailActionInputModel.To,
             Bcc = mailActionInputModel.Bcc,
             Body = GetTemplate(mailActionInputModel.TemplateKey, mailActionInputModel.DynamicObject),
             FromEmail = _confSection["from"].ToString(),
             FromName = _confSection["sender"].ToString(),
         }));
     }
     catch (System.Exception ex)
     {
         throw new BusinessOperationException(new BusinesOperationExceptionModel()
         {
             MethodName      = "Send",
             ClassName       = "BaseMailOperation",
             Code            = "IEmailOutput",
             OriginalMessage = ex.ToString()
         });
     }
 }
Ejemplo n.º 18
0
 public async Task SendTemplateAsync()
 {
     await _sender.SendAsync(MessageTemplate);
 }
Ejemplo n.º 19
0
 public static void Send(this Mail msg, IMailSender sender)
 {
     sender.SendAsync(msg);
 }