コード例 #1
0
        private async Task SendFirstEmail(Employee employee)
        {
            var emailAddress = new EmailAddress(employee.Name, employee.Email);
            var emailMessage = new EmailMessage();

            try
            {
                emailMessage.FromAddresses.Add(new EmailAddress());
                emailMessage.ToAddresses.Add(emailAddress);
                emailMessage.Subject = "Praca";

                if (production)
                {
                    emailMessage.Content = EmailText.EmailToEmployee;
                }
                else
                {
                    const string filePath = @"Services\EmailService\EmailText\EmailToEmployee.txt";
                    using var fileStream   = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                    using var streamReader = new StreamReader(fileStream, Encoding.UTF8);

                    emailMessage.Content = streamReader.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                ExceptionAlert(e.Message);
            }

            await _emailProvider.Send(emailMessage);
        }
コード例 #2
0
        public async Task SendAccountActivation(SendAccountActivationRequest request)
        {
            var activationToken = string.Empty;

            UserEntity user;

            using (var uow = _uowFactory.GetUnitOfWork())
            {
                user = await uow.UserRepo.GetUserById(new Infrastructure.Repositories.UserRepo.Models.GetUserByIdRequest()
                {
                    Id = request.UserId
                });

                activationToken = GenerateUniqueUserToken(uow);

                await uow.UserRepo.CreateUserToken(new Infrastructure.Repositories.UserRepo.Models.CreateUserTokenRequest()
                {
                    User_Id    = request.UserId,
                    Token      = new Guid(activationToken),
                    Type_Id    = (int)TokenTypeEnum.AccountActivation,
                    Created_By = ApplicationConstants.SystemUserId,
                });

                uow.Commit();
            }

            var configuration = await _cache.Configuration();

            var baseUrl = _httpContextAccessor.HttpContext.Request.GetBaseUrl();

            var templates = await _cache.EmailTemplates();

            var templateEntity = templates.FirstOrDefault(t => t.Key == EmailTemplateKeys.AccountActivation);

            var template = new AccountActivationTemplate(templateEntity.Body)
            {
                ActivationUrl  = $"{baseUrl}/activate-account?token={activationToken}",
                ApplicationUrl = baseUrl
            };

            await _emailProvider.Send(new Infrastructure.Email.Models.SendRequest()
            {
                FromAddress = configuration.System_From_Email_Address,
                ToAddress   = user.Email_Address,
                Subject     = template.Subject,
                Body        = template.GetHTMLContent()
            });
        }
コード例 #3
0
ファイル: Facade.cs プロジェクト: sidkcr/design-patterns
        public bool Notify(string message, string address)
        {
            bool isMessageSent = messageProvider.Send(message, address);
            bool isEmailSent   = emailProvider.Send(message, address);

            return(isMessageSent && isEmailSent);
        }
コード例 #4
0
ファイル: EmailService.cs プロジェクト: t9mike/vault
 private void DeliverAndLog(EmailMessage email)
 {
     if (email != null)
     {
         _sender.Send(email);
     }
     _repository.Save(email);
 }
コード例 #5
0
        public Task Handle(RegisterUserCommand command)
        {
            var emailMessage = new EmailMessage
            {
                Content = _templateBuilder.Build(Template.Get(), new TemplateModel
                {
                    Title    = "Email Confirmation",
                    Content  = "Please confirm your email by clicking like below.",
                    Link     = $"{command.SiteAddress}/Account/ConfirmEmail?emailId={command.EmailId}&token={command.ConfirmationToken}",
                    LinkName = "Confirm"
                })
            };

            emailMessage.To.Add(command.EmailId);
            emailMessage.Subject = "Email Confirmation";
            _emailProvider.Send(1, emailMessage);

            return(Task.CompletedTask);
        }
コード例 #6
0
 public async Task Handle(ProcedimentoAgendadoEvent notification, CancellationToken cancellationToken)
 {
     var email           = notification.Procedimento.Solicitante.Email.EnderecoCompleto;
     var nomeCleinte     = notification.Procedimento.Solicitante.Nome;
     var servico         = notification.Procedimento.TipoProcedimento.Descricao;
     var dataAgendamento = notification.Procedimento.Data;
     var htmlMensagem    = $"Prezado(a), {nomeCleinte}.<br/> Seu agendamento para o servico {servico}," +
                           $"foi realizado com sucesso.<br/>Compareça em nossa loja em {dataAgendamento}.<br/>" +
                           $"Atenciosamente,<br/>";
     await _email.Send(email, htmlMensagem);
 }
コード例 #7
0
        public void SendConfirmation(DeleteSyncEmailModel model)
        {
            var message = new MailMessage();

            message.To.Add(model.To);
            if (!string.IsNullOrEmpty(model.From))
            {
                message.From = new MailAddress(model.From);
            }
            message.Subject = model.Subject;
            message.Body    = model.Body;

            _emailProvider.Send(message);
        }
コード例 #8
0
        public void Process(string inputFile)
        {
            var reader = new CSVReaderWriter();

            reader.Open(inputFile, CSVReaderWriter.Mode.Read);

            string column1, column2;

            while (reader.Read(out column1, out column2))
            {
                emailProvider.Send(column1, column2);
            }

            reader.Close();
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: vterceros/PatternFactory
 private static void SendEmail(string Provider)
 {
     try
     {
         IEmailProvider emailProvider = EmailProviderFactory.EmailProviderFactory.GetProvider(Provider);
         emailProvider.Send("hello", (new string[] { "*****@*****.**", "*****@*****.**" }), null, "subject");
     }
     catch (NotSupportedException ex)
     {
         Console.WriteLine(string.Format("Not supported with message '{0}'", ex.Message));
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
コード例 #10
0
        public async Task <IActionResult> Register(UserRegistrationViewModel model)
        {
            if (!(await _roleManager.RoleExistsAsync(Roles.Professional)))
            {
                await _roleManager.CreateAsync(new IdentityRole(Roles.Professional));
            }

            var professional = new User
            {
                UserName  = model.Email,
                Email     = model.Email,
                LastName  = model.LastName,
                FirstName = model.FirstName
            };

            var result = await _userManager.CreateAsync(professional, model.Password);

            if (!result.Succeeded)
            {
                return(BadRequest(result));
            }

            //Send Email
            var token = await _userManager.GenerateEmailConfirmationTokenAsync(professional);

            var confirmEmailUrl = "https://localhost:5001/Email-confirm";
            var uriBuilder      = new UriBuilder(confirmEmailUrl);
            var query           = HttpUtility.ParseQueryString(uriBuilder.Query);

            query["token"]   = token;
            query["userid"]  = professional.Id;
            uriBuilder.Query = query.ToString();
            var urlString = uriBuilder.ToString();

            var emailBody = $"Please confirm your email by clicking on the link below {urlString}";

            _emailProvider.Send(model.Email, emailBody, _emailOptions.Value);

            //////////////////

            var userFromDb = await _userManager.FindByNameAsync(professional.UserName);

            await _userManager.AddToRoleAsync(userFromDb, Roles.Professional);

            return(View());
        }
コード例 #11
0
ファイル: NewsletterJob.cs プロジェクト: roanvonb/Ombi
        public async Task Start(NewsletterSettings settings, bool test)
        {
            if (!settings.Enabled)
            {
                return;
            }
            var template = await _templateRepo.GetTemplate(NotificationAgent.Email, NotificationType.Newsletter);

            if (!template.Enabled)
            {
                return;
            }

            var emailSettings = await _emailSettings.GetSettingsAsync();

            if (!ValidateConfiguration(emailSettings))
            {
                return;
            }

            var customization = await _customizationSettings.GetSettingsAsync();

            // Get the Content
            var plexContent = _plex.GetAll().Include(x => x.Episodes).AsNoTracking();
            var embyContent = _emby.GetAll().Include(x => x.Episodes).AsNoTracking();

            var addedLog              = _recentlyAddedLog.GetAll();
            var addedPlexMovieLogIds  = addedLog.Where(x => x.Type == RecentlyAddedType.Plex && x.ContentType == ContentType.Parent).Select(x => x.ContentId);
            var addedEmbyMoviesLogIds = addedLog.Where(x => x.Type == RecentlyAddedType.Emby && x.ContentType == ContentType.Parent).Select(x => x.ContentId);

            var addedPlexEpisodesLogIds = addedLog.Where(x => x.Type == RecentlyAddedType.Plex && x.ContentType == ContentType.Episode).Select(x => x.ContentId);
            var addedEmbyEpisodesLogIds = addedLog.Where(x => x.Type == RecentlyAddedType.Emby && x.ContentType == ContentType.Episode).Select(x => x.ContentId);

            // Filter out the ones that we haven't sent yet
            var plexContentMoviesToSend = plexContent.Where(x => x.Type == PlexMediaTypeEntity.Movie && !addedPlexMovieLogIds.Contains(x.Id));
            var embyContentMoviesToSend = embyContent.Where(x => x.Type == EmbyMediaType.Movie && !addedEmbyMoviesLogIds.Contains(x.Id));

            var plexEpisodesToSend = _plex.GetAllEpisodes().Include(x => x.Series).Where(x => !addedPlexEpisodesLogIds.Contains(x.Id)).AsNoTracking();
            var embyEpisodesToSend = _emby.GetAllEpisodes().Include(x => x.Series).Where(x => !addedEmbyEpisodesLogIds.Contains(x.Id)).AsNoTracking();

            var body = string.Empty;

            if (test)
            {
                var plexm = plexContent.Where(x => x.Type == PlexMediaTypeEntity.Movie).OrderByDescending(x => x.AddedAt).Take(10);
                var embym = embyContent.Where(x => x.Type == EmbyMediaType.Movie).OrderByDescending(x => x.AddedAt).Take(10);
                var plext = _plex.GetAllEpisodes().Include(x => x.Series).OrderByDescending(x => x.Series.AddedAt).Take(10);
                var embyt = _emby.GetAllEpisodes().Include(x => x.Series).OrderByDescending(x => x.AddedAt).Take(10);
                body = await BuildHtml(plexm, embym, plext, embyt);
            }
            else
            {
                body = await BuildHtml(plexContentMoviesToSend, embyContentMoviesToSend, plexEpisodesToSend, embyEpisodesToSend);

                if (body.IsNullOrEmpty())
                {
                    return;
                }
            }

            if (!test)
            {
                // Get the users to send it to
                var users = await _userManager.GetUsersInRoleAsync(OmbiRoles.RecievesNewsletter);

                if (!users.Any())
                {
                    return;
                }
                var emailTasks = new List <Task>();
                foreach (var user in users)
                {
                    if (user.Email.IsNullOrEmpty())
                    {
                        continue;
                    }

                    var messageContent = ParseTemplate(template, customization, user);
                    var email          = new NewsletterTemplate();

                    var html = email.LoadTemplate(messageContent.Subject, messageContent.Message, body, customization.Logo);

                    emailTasks.Add(_email.Send(
                                       new NotificationMessage {
                        Message = html, Subject = messageContent.Subject, To = user.Email
                    },
                                       emailSettings));
                }

                // Now add all of this to the Recently Added log
                var recentlyAddedLog = new HashSet <RecentlyAddedLog>();
                foreach (var p in plexContentMoviesToSend)
                {
                    recentlyAddedLog.Add(new RecentlyAddedLog
                    {
                        AddedAt     = DateTime.Now,
                        Type        = RecentlyAddedType.Plex,
                        ContentType = ContentType.Parent,
                        ContentId   = p.Id
                    });
                }

                foreach (var p in plexEpisodesToSend)
                {
                    recentlyAddedLog.Add(new RecentlyAddedLog
                    {
                        AddedAt     = DateTime.Now,
                        Type        = RecentlyAddedType.Plex,
                        ContentType = ContentType.Episode,
                        ContentId   = p.Id
                    });
                }

                foreach (var e in embyContentMoviesToSend)
                {
                    if (e.Type == EmbyMediaType.Movie)
                    {
                        recentlyAddedLog.Add(new RecentlyAddedLog
                        {
                            AddedAt     = DateTime.Now,
                            Type        = RecentlyAddedType.Emby,
                            ContentType = ContentType.Parent,
                            ContentId   = e.Id
                        });
                    }
                }

                foreach (var p in embyEpisodesToSend)
                {
                    recentlyAddedLog.Add(new RecentlyAddedLog
                    {
                        AddedAt     = DateTime.Now,
                        Type        = RecentlyAddedType.Emby,
                        ContentType = ContentType.Episode,
                        ContentId   = p.Id
                    });
                }
                await _recentlyAddedLog.AddRange(recentlyAddedLog);

                await Task.WhenAll(emailTasks.ToArray());
            }
            else
            {
                var admins = await _userManager.GetUsersInRoleAsync(OmbiRoles.Admin);

                foreach (var a in admins)
                {
                    if (a.Email.IsNullOrEmpty())
                    {
                        continue;
                    }
                    var messageContent = ParseTemplate(template, customization, a);

                    var email = new NewsletterTemplate();

                    var html = email.LoadTemplate(messageContent.Subject, messageContent.Message, body, customization.Logo);

                    await _email.Send(
                        new NotificationMessage { Message = html, Subject = messageContent.Subject, To = a.Email },
                        emailSettings);
                }
            }
        }
 public void MoveToBucket(string bucketId, List <ShippingBill> shippingBills)
 {
     emailProvider.Send(new Email());
     throw new NotImplementedException("UPS");
 }
コード例 #13
0
ファイル: EmailMessage.cs プロジェクト: dolani/CodeTorch
       public void Send()
       {
           IEmailProvider email = EmailService.GetInstance().GetProvider(null);
           email.Send(this);
 
       }
コード例 #14
0
ファイル: NewsletterJob.cs プロジェクト: x-limitless-x/Ombi
        public async Task Start(NewsletterSettings settings, bool test)
        {
            if (!settings.Enabled)
            {
                return;
            }
            var template = await _templateRepo.GetTemplate(NotificationAgent.Email, NotificationType.Newsletter);

            if (!template.Enabled)
            {
                return;
            }

            var emailSettings = await _emailSettings.GetSettingsAsync();

            if (!ValidateConfiguration(emailSettings))
            {
                return;
            }

            try
            {
                var customization = await _customizationSettings.GetSettingsAsync();

                // Get the Content
                var plexContent   = _plex.GetAll().Include(x => x.Episodes).AsNoTracking();
                var embyContent   = _emby.GetAll().Include(x => x.Episodes).AsNoTracking();
                var lidarrContent = _lidarrAlbumRepository.GetAll().Where(x => x.FullyAvailable).AsNoTracking();

                var addedLog              = _recentlyAddedLog.GetAll();
                var addedPlexMovieLogIds  = addedLog.Where(x => x.Type == RecentlyAddedType.Plex && x.ContentType == ContentType.Parent).Select(x => x.ContentId).ToHashSet();
                var addedEmbyMoviesLogIds = addedLog.Where(x => x.Type == RecentlyAddedType.Emby && x.ContentType == ContentType.Parent).Select(x => x.ContentId).ToHashSet();
                var addedAlbumLogIds      = addedLog.Where(x => x.Type == RecentlyAddedType.Lidarr && x.ContentType == ContentType.Album).Select(x => x.AlbumId).ToHashSet();

                var addedPlexEpisodesLogIds =
                    addedLog.Where(x => x.Type == RecentlyAddedType.Plex && x.ContentType == ContentType.Episode);
                var addedEmbyEpisodesLogIds =
                    addedLog.Where(x => x.Type == RecentlyAddedType.Emby && x.ContentType == ContentType.Episode);


                // Filter out the ones that we haven't sent yet
                var plexContentMoviesToSend   = plexContent.Where(x => x.Type == PlexMediaTypeEntity.Movie && x.HasTheMovieDb && !addedPlexMovieLogIds.Contains(StringHelper.IntParseLinq(x.TheMovieDbId)));
                var embyContentMoviesToSend   = embyContent.Where(x => x.Type == EmbyMediaType.Movie && x.HasTheMovieDb && !addedEmbyMoviesLogIds.Contains(StringHelper.IntParseLinq(x.TheMovieDbId)));
                var lidarrContentAlbumsToSend = lidarrContent.Where(x => !addedAlbumLogIds.Contains(x.ForeignAlbumId)).ToHashSet();
                _log.LogInformation("Plex Movies to send: {0}", plexContentMoviesToSend.Count());
                _log.LogInformation("Emby Movies to send: {0}", embyContentMoviesToSend.Count());
                _log.LogInformation("Albums to send: {0}", lidarrContentAlbumsToSend.Count());

                var plexEpisodesToSend =
                    FilterPlexEpisodes(_plex.GetAllEpisodes().Include(x => x.Series).Where(x => x.Series.HasTvDb).AsNoTracking(), addedPlexEpisodesLogIds);
                var embyEpisodesToSend = FilterEmbyEpisodes(_emby.GetAllEpisodes().Include(x => x.Series).Where(x => x.Series.HasTvDb).AsNoTracking(),
                                                            addedEmbyEpisodesLogIds);

                _log.LogInformation("Plex Episodes to send: {0}", plexEpisodesToSend.Count());
                _log.LogInformation("Emby Episodes to send: {0}", embyEpisodesToSend.Count());
                var plexSettings = await _plexSettings.GetSettingsAsync();

                var embySettings = await _embySettings.GetSettingsAsync();

                var body = string.Empty;
                if (test)
                {
                    var plexm  = plexContent.Where(x => x.Type == PlexMediaTypeEntity.Movie).OrderByDescending(x => x.AddedAt).Take(10);
                    var embym  = embyContent.Where(x => x.Type == EmbyMediaType.Movie).OrderByDescending(x => x.AddedAt).Take(10);
                    var plext  = _plex.GetAllEpisodes().Include(x => x.Series).OrderByDescending(x => x.Series.AddedAt).Take(10).ToHashSet();
                    var embyt  = _emby.GetAllEpisodes().Include(x => x.Series).OrderByDescending(x => x.AddedAt).Take(10).ToHashSet();
                    var lidarr = lidarrContent.OrderByDescending(x => x.AddedAt).Take(10).ToHashSet();
                    body = await BuildHtml(plexm, embym, plext, embyt, lidarr, settings, embySettings, plexSettings);
                }
                else
                {
                    body = await BuildHtml(plexContentMoviesToSend, embyContentMoviesToSend, plexEpisodesToSend, embyEpisodesToSend, lidarrContentAlbumsToSend, settings, embySettings, plexSettings);

                    if (body.IsNullOrEmpty())
                    {
                        return;
                    }
                }

                if (!test)
                {
                    // Get the users to send it to
                    var users = await _userManager.GetUsersInRoleAsync(OmbiRoles.ReceivesNewsletter);

                    if (!users.Any())
                    {
                        return;
                    }

                    foreach (var emails in settings.ExternalEmails)
                    {
                        users.Add(new OmbiUser
                        {
                            UserName = emails,
                            Email    = emails
                        });
                    }

                    var messageContent = ParseTemplate(template, customization);
                    var email          = new NewsletterTemplate();

                    var html = email.LoadTemplate(messageContent.Subject, messageContent.Message, body, customization.Logo);

                    var bodyBuilder = new BodyBuilder
                    {
                        HtmlBody = html,
                    };

                    var message = new MimeMessage
                    {
                        Body    = bodyBuilder.ToMessageBody(),
                        Subject = messageContent.Subject
                    };

                    foreach (var user in users)
                    {
                        // Get the users to send it to
                        if (user.Email.IsNullOrEmpty())
                        {
                            continue;
                        }
                        // BCC the messages
                        message.Bcc.Add(new MailboxAddress(user.Email, user.Email));
                    }

                    // Send the email
                    await _email.Send(message, emailSettings);

                    // Now add all of this to the Recently Added log
                    var recentlyAddedLog = new HashSet <RecentlyAddedLog>();
                    foreach (var p in plexContentMoviesToSend)
                    {
                        recentlyAddedLog.Add(new RecentlyAddedLog
                        {
                            AddedAt     = DateTime.Now,
                            Type        = RecentlyAddedType.Plex,
                            ContentType = ContentType.Parent,
                            ContentId   = StringHelper.IntParseLinq(p.TheMovieDbId),
                        });
                    }

                    foreach (var p in plexEpisodesToSend)
                    {
                        recentlyAddedLog.Add(new RecentlyAddedLog
                        {
                            AddedAt       = DateTime.Now,
                            Type          = RecentlyAddedType.Plex,
                            ContentType   = ContentType.Episode,
                            ContentId     = StringHelper.IntParseLinq(p.Series.TvDbId),
                            EpisodeNumber = p.EpisodeNumber,
                            SeasonNumber  = p.SeasonNumber
                        });
                    }
                    foreach (var e in embyContentMoviesToSend)
                    {
                        if (e.Type == EmbyMediaType.Movie)
                        {
                            recentlyAddedLog.Add(new RecentlyAddedLog
                            {
                                AddedAt     = DateTime.Now,
                                Type        = RecentlyAddedType.Emby,
                                ContentType = ContentType.Parent,
                                ContentId   = StringHelper.IntParseLinq(e.TheMovieDbId),
                            });
                        }
                    }

                    foreach (var p in embyEpisodesToSend)
                    {
                        recentlyAddedLog.Add(new RecentlyAddedLog
                        {
                            AddedAt       = DateTime.Now,
                            Type          = RecentlyAddedType.Emby,
                            ContentType   = ContentType.Episode,
                            ContentId     = StringHelper.IntParseLinq(p.Series.TvDbId),
                            EpisodeNumber = p.EpisodeNumber,
                            SeasonNumber  = p.SeasonNumber
                        });
                    }
                    await _recentlyAddedLog.AddRange(recentlyAddedLog);
                }
                else
                {
                    var admins = await _userManager.GetUsersInRoleAsync(OmbiRoles.Admin);

                    foreach (var a in admins)
                    {
                        if (a.Email.IsNullOrEmpty())
                        {
                            continue;
                        }
                        var messageContent = ParseTemplate(template, customization);

                        var email = new NewsletterTemplate();

                        var html = email.LoadTemplate(messageContent.Subject, messageContent.Message, body, customization.Logo);

                        await _email.Send(
                            new NotificationMessage { Message = html, Subject = messageContent.Subject, To = a.Email },
                            emailSettings);
                    }
                }
            }
            catch (Exception e)
            {
                _log.LogError(e, "Error when attempting to create newsletter");
                throw;
            }
        }
コード例 #15
0
        public override void Execute(System.Data.Common.DbTransaction tran, string workflowCode, string fromWorkflowStepCode, string toWorkflowStepCode, string entityID, string comment, string userName)
        {
            EmailAddress address  = null;
            Workflow     workflow = Workflow.GetWorkflowByCode(workflowCode);
            //select template
            Template contentTemplate = GetTemplate(tran, workflowCode, fromWorkflowStepCode, toWorkflowStepCode, entityID, comment, userName);
            DateMode dateMode        = Configuration.GetInstance().App.DateMode;

            if (contentTemplate != null)
            {
                DataTable subjects    = GetSubjects(tran, workflowCode, fromWorkflowStepCode, toWorkflowStepCode, entityID, comment, userName);
                DataTable from        = GetAddresses(tran, "from", workflowCode, fromWorkflowStepCode, toWorkflowStepCode, entityID, comment, userName);
                DataTable cc          = GetAddresses(tran, "cc", workflowCode, fromWorkflowStepCode, toWorkflowStepCode, entityID, comment, userName);
                DataTable bcc         = GetAddresses(tran, "bcc", workflowCode, fromWorkflowStepCode, toWorkflowStepCode, entityID, comment, userName);
                DataTable to          = GetAddresses(tran, "to", workflowCode, fromWorkflowStepCode, toWorkflowStepCode, entityID, comment, userName);
                DataTable replyto     = GetAddresses(tran, "to", workflowCode, fromWorkflowStepCode, toWorkflowStepCode, entityID, comment, userName);
                DataTable attachments = GetAttachments(tran, workflowCode, fromWorkflowStepCode, toWorkflowStepCode, entityID, comment, userName);
                DataTable mailitems   = GetMailItems(to);

                Hashtable contentItems = GetContentItems(tran, contentTemplate, workflowCode, fromWorkflowStepCode, toWorkflowStepCode, entityID, comment, userName);

                IEmailProvider email = null;

                //individual emails for each tos
                foreach (DataRow mail in mailitems.Rows)
                {
                    EmailMessage message = new EmailMessage();



                    if (email == null)
                    {
                        //set connection
                        message.EmailConnection = this.EmailConnection;
                        email = EmailService.GetInstance().GetProvider(message);
                    }


                    message.Subject    = GetSubject(mail, subjects);
                    message.Body       = GetBody(mail, contentTemplate, contentItems);
                    message.EntityID   = entityID;
                    message.EntityType = workflow.EntityName;
                    message.IsBodyHtml = this.IsBodyHtml;
                    message.Priority   = this.Priority;
                    message.Template   = contentTemplate.Name;


                    //from
                    DataRow[] fromList = from.Select(String.Format("(TO = '{0}') OR (TO IS NULL)", mail["TO"]));
                    if (fromList.Length > 0)
                    {
                        DataRow a = fromList[0];

                        address             = new EmailAddress();
                        address.DisplayName = a["DisplayName"].ToString();
                        address.Address     = a["Address"].ToString();

                        message.From = address;
                    }

                    //to
                    if (this.ToAddressSendMode == EmailAddressSendMode.Individual)
                    {
                        address             = new EmailAddress();
                        address.DisplayName = mail["DisplayName"].ToString();
                        address.Address     = mail["Address"].ToString();

                        message.To.Add(address);
                    }
                    else
                    {
                        foreach (DataRow a in to.Rows)
                        {
                            address             = new EmailAddress();
                            address.DisplayName = a["DisplayName"].ToString();
                            address.Address     = a["Address"].ToString();

                            message.To.Add(address);
                        }
                    }


                    //cc
                    foreach (DataRow a in cc.Select(String.Format("(TO = '{0}') OR (TO IS NULL)", mail["TO"])))
                    {
                        address             = new EmailAddress();
                        address.DisplayName = a["DisplayName"].ToString();
                        address.Address     = a["Address"].ToString();

                        message.CC.Add(address);
                    }

                    //bcc
                    foreach (DataRow a in bcc.Select(String.Format("(TO = '{0}') OR (TO IS NULL)", mail["TO"])))
                    {
                        address             = new EmailAddress();
                        address.DisplayName = a["DisplayName"].ToString();
                        address.Address     = a["Address"].ToString();

                        message.BCC.Add(address);
                    }

                    foreach (DataRow a in replyto.Select(String.Format("(TO = '{0}') OR (TO IS NULL)", mail["TO"])))
                    {
                        address             = new EmailAddress();
                        address.DisplayName = a["DisplayName"].ToString();
                        address.Address     = a["Address"].ToString();

                        message.ReplyTo.Add(address);
                    }

                    //attachments
                    foreach (DataRow a in attachments.Select(String.Format("(TO = '{0}') OR (TO IS NULL)", mail["TO"])))
                    {
                        EmailAttachment attachment = new EmailAttachment();
                        attachment.DocumentID = a["DocumentID"].ToString();

                        message.Attachments.Add(attachment);
                    }

                    email.Send(message);
                }
            }
            else
            {
                throw new ApplicationException("No Email Template found");
            }
        }
コード例 #16
0
 public void Send()
 {
     _emailProvider.Send();
 }
コード例 #17
0
        public async Task Start(NewsletterSettings settings, bool test)
        {
            if (!settings.Enabled)
            {
                return;
            }
            var template = await _templateRepo.GetTemplate(NotificationAgent.Email, NotificationType.Newsletter);

            if (!template.Enabled)
            {
                return;
            }

            await _notification.Clients.Clients(NotificationHub.AdminConnectionIds)
            .SendAsync(NotificationHub.NotificationEvent, "Newsletter Started");

            var emailSettings = await _emailSettings.GetSettingsAsync();

            if (!ValidateConfiguration(emailSettings))
            {
                await _notification.Clients.Clients(NotificationHub.AdminConnectionIds)
                .SendAsync(NotificationHub.NotificationEvent, "Newsletter Email Settings Not Configured");

                return;
            }

            try
            {
                var plexSettings = await _plexSettings.GetSettingsAsync();

                var embySettings = await _embySettings.GetSettingsAsync();

                var jellyfinSettings = await _jellyfinSettings.GetSettingsAsync();

                var customization = await _customizationSettings.GetSettingsAsync();

                var moviesContents = new List <IMediaServerContent>();
                var seriesContents = new List <IMediaServerEpisode>();
                if (plexSettings.Enable)
                {
                    moviesContents.AddRange(await GetMoviesContent(_plex, test));
                    seriesContents.AddRange(GetSeriesContent(_plex, test));
                }
                if (embySettings.Enable)
                {
                    moviesContents.AddRange(await GetMoviesContent(_emby, test));
                    seriesContents.AddRange(GetSeriesContent(_emby, test));
                }
                if (jellyfinSettings.Enable)
                {
                    moviesContents.AddRange(await GetMoviesContent(_jellyfin, test));
                    seriesContents.AddRange(GetSeriesContent(_jellyfin, test));
                }

                var albumsContents = GetMusicContent(_lidarrAlbumRepository, test);

                var body = await BuildHtml(moviesContents, seriesContents, albumsContents, settings);

                if (body.IsNullOrEmpty())
                {
                    return;
                }

                if (!test)
                {
                    var users = new List <OmbiUser>();
                    foreach (var emails in settings.ExternalEmails)
                    {
                        users.Add(new OmbiUser
                        {
                            UserName = emails,
                            Email    = emails
                        });
                    }

                    // Get the users to send it to
                    users.AddRange(await _userManager.GetUsersInRoleAsync(OmbiRoles.ReceivesNewsletter));
                    if (!users.Any())
                    {
                        return;
                    }

                    var messageContent = ParseTemplate(template, customization);
                    var email          = new NewsletterTemplate();

                    foreach (var user in users.DistinctBy(x => x.Email))
                    {                        // Get the users to send it to
                        if (user.Email.IsNullOrEmpty())
                        {
                            continue;
                        }

                        var url  = GenerateUnsubscribeLink(customization.ApplicationUrl, user.Id);
                        var html = email.LoadTemplate(messageContent.Subject, messageContent.Message, body, customization.Logo, url);

                        var bodyBuilder = new BodyBuilder
                        {
                            HtmlBody = html,
                        };

                        var message = new MimeMessage
                        {
                            Body    = bodyBuilder.ToMessageBody(),
                            Subject = messageContent.Subject
                        };

                        // Send the message to the user
                        message.To.Add(new MailboxAddress(user.Email.Trim(), user.Email.Trim()));

                        // Send the email
                        await _email.Send(message, emailSettings);
                    }

                    // Now add all of this to the Recently Added log
                    var recentlyAddedLog = new HashSet <RecentlyAddedLog>();
                    AddToRecentlyAddedLog(moviesContents, recentlyAddedLog);
                    AddToRecentlyAddedLog(seriesContents, recentlyAddedLog);
                    await _recentlyAddedLog.AddRange(recentlyAddedLog);
                }
                else
                {
                    var admins = await _userManager.GetUsersInRoleAsync(OmbiRoles.Admin);

                    foreach (var a in admins)
                    {
                        if (a.Email.IsNullOrEmpty())
                        {
                            continue;
                        }

                        var unsubscribeLink = GenerateUnsubscribeLink(customization.ApplicationUrl, a.Id);

                        var messageContent = ParseTemplate(template, customization);

                        var email = new NewsletterTemplate();

                        var html = email.LoadTemplate(messageContent.Subject, messageContent.Message, body, customization.Logo, unsubscribeLink);

                        await _email.Send(
                            new NotificationMessage { Message = html, Subject = messageContent.Subject, To = a.Email },
                            emailSettings);
                    }
                }
            }
            catch (Exception e)
            {
                await _notification.Clients.Clients(NotificationHub.AdminConnectionIds)
                .SendAsync(NotificationHub.NotificationEvent, "Newsletter Failed");

                _log.LogError(e, "Error when attempting to create newsletter");
                throw;
            }

            await _notification.Clients.Clients(NotificationHub.AdminConnectionIds)
            .SendAsync(NotificationHub.NotificationEvent, "Newsletter Finished");
        }
コード例 #18
0
        private void DeliveryCycle(ParallelOptions options, EmailMessage message, ParallelLoopState state)
        {
            if (state.ShouldExitCurrentIteration)
            {
                _backlog.Enqueue(message);
            }
            else
            {
                if (message.DeliveryTime.HasValue)
                {
                    if (message.DeliveryTime.Value.ToUniversalTime() > DateTime.UtcNow)
                    {
                        if (_outgoing.IsAddingCompleted)
                        {
                            _backlog.Enqueue(message);
                        }
                        else
                        {
                            _outgoing.Add(message);
                        }
                        return;
                    }
                }

                if (_provider.Send(message))
                {
                    Interlocked.Increment(ref _delivered);
                }
                else
                {
                    // Back seat in the queue
                    if (_config.RetryPolicy != null)
                    {
                        var decision = _config.RetryPolicy.DecideOn(message);
                        switch (decision)
                        {
                        case DeliveryRetryDecision.RetryImmediately:
                            DeliveryCycle(options, message, state);
                            break;

                        case DeliveryRetryDecision.SendToBackOfQueue:
                            _outgoing.Add(message);
                            break;

                        case DeliveryRetryDecision.SendToBacklog:
                            _backlog.Enqueue(message);
                            break;

                        case DeliveryRetryDecision.SendToUndeliverableFolder:
                            Undeliverable(message);
                            break;

                        case DeliveryRetryDecision.Destroy:
                            break;

                        default:
                            throw new ArgumentOutOfRangeException();
                        }
                    }
                    else
                    {
                        _outgoing.Add(message);
                    }
                }
            }

            options.CancellationToken.ThrowIfCancellationRequested();
        }
コード例 #19
0
ファイル: Outbox.cs プロジェクト: mercadolar/carupano
 public void Send(SendNotification notif)
 {
     Sender.Send(notif.Template, _email, notif.MergeData);
 }