Exemplo n.º 1
0
        public void SmtpMailerUseAuthentication(string username, string password, bool shouldUseAuthentication)
        {
            var renderer = RazorRendererFactory.MakeInstance(new ConfigurationBuilder().Build());
            var mailer   = new SmtpMailer(renderer, "dummy", 1, username, password);

            Assert.Equal(mailer.UseSMTPAuthentication(), shouldUseAuthentication);
        }
Exemplo n.º 2
0
        private static async Task SendConfirmationMail(string from, string fromPassword, string customerMail, string customerName)
        {
            // Construct the e-mail model
            EmailComposer <WelcomeMailModel> composer = new EmailComposer <WelcomeMailModel>();
            EmailRequest <WelcomeMailModel>  request  = composer
                                                        .SetModel(new WelcomeMailModel {
                Email = customerMail, Name = customerName
            })
                                                        .SetSubject("Welcome to the company!")
                                                        .SetFrom("*****@*****.**")
                                                        .SetTo(customerMail)
                                                        .Build();

            // Creating the body using the following components:
            // * Use Scriban as the template syntax
            // * Store templates in the project under the 'Templates' application directory
            // * Map e-mail templates by the mail model name (WelcomeMailModel -> Welcome.sbnhtml)
            IMailBodyBuilder builder = new MailBodyBuilder(
                new ScribanCompiler(),
                new AppDirectoryTemplateProvider("Templates", ".sbnhtml"),
                new ViewModelTemplateResolver());

            EmailRequest populatedRequest = await builder.BuildAsync(request);

            // When using a gmail account: https://stackoverflow.com/a/25215834/1842261
            SmtpCredentials credentials = new("smtp.gmail.com", "587", "false", "true", from, fromPassword);
            IMailer         mailer      = new SmtpMailer(credentials);
            await mailer.SendMailAsync(populatedRequest);
        }
Exemplo n.º 3
0
        public async Task Smtp_SendTemplateMail_SimulateDependencyInjection_ShouldSend()
        {
            SmtpCredentials credentials = new("smtp.mailtrap.io", "587", "false", "true", "d3538ae47a016d", "d4add3690c408c");

            EmailComposer <TestMailModel> composer = new();
            EmailRequest <TestMailModel>  request  = composer
                                                     .SetModel(new TestMailModel {
                Email = "*****@*****.**", Name = "Guy Gadbois"
            })
                                                     .SetSubject("Hello world")
                                                     .SetFrom("*****@*****.**")
                                                     .SetTo("*****@*****.**")
                                                     .SetCc("*****@*****.**")
                                                     .SetBcc("*****@*****.**")
                                                     .Build();

            IMailer mailer = new SmtpMailer(credentials);

            IMailBodyBuilder builder = new MailBodyBuilder(
                new ScribanCompiler(),
                new AppDirectoryTemplateProvider("Templates", ".sbnhtml"),
                new ViewModelTemplateResolver());

            EmailRequest populatedRequest = await builder.BuildAsync(request);

            await mailer.SendMailAsync(populatedRequest);
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    //await SmtpMailer.Instance(ConfigurationManagerConstant.WebConfiguration).SendAsyncRegisterNotification(user.Email);
                    SmtpMailer.Instance(WebConfigurationManager.OpenWebConfiguration("~/web.config")).SendRegisterNotification(user.Email);

                    return(RedirectToAction("List", "Workflow"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(PartialView("Register", model));
        }
Exemplo n.º 5
0
        public async Task SmtpMailerRenderSucessful()
        {
            var renderer = RazorRendererFactory.MakeInstance(new ConfigurationBuilder().Build());
            var mailer   = new SmtpMailer(renderer, "dummy", 1, "dummy", "dummy");

            string message = await mailer.RenderAsync(
                new GenericHtmlMailable()
                .Subject("test")
                .From("*****@*****.**")
                .To("*****@*****.**")
                .Html("<html></html>")
                );

            Assert.Equal("<html></html>", message);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Register Coravel's mailer using the Smtp Mailer.
        /// </summary>
        /// <param name="services"></param>
        /// <param name="config"></param>
        /// <param name="certCallback"></param>
        public static void AddSmtpMailer(this IServiceCollection services, IConfiguration config, RemoteCertificateValidationCallback certCallback)
        {
            var           globalFrom = GetGlobalFromRecipient(config);
            RazorRenderer renderer   = RazorRendererFactory.MakeInstance(config);
            IMailer       mailer     = new SmtpMailer(
                renderer,
                config.GetValue <string>("Coravel:Mail:Host", ""),
                config.GetValue <int>("Coravel:Mail:Port", 0),
                config.GetValue <string>("Coravel:Mail:Username", ""),
                config.GetValue <string>("Coravel:Mail:Password", ""),
                globalFrom,
                certCallback
                );

            services.AddSingleton <IMailer>(mailer);
        }
Exemplo n.º 7
0
 private void ClickMethodSendEmail()
 {
     try
     {
         var mail = SmtpMailer.Instance();
         mail.SendMail(Email, Title, SqlQuerry);
         this.CloseAction();
         MessageBoxImage  icon   = MessageBoxImage.Information;
         MessageBoxButton button = MessageBoxButton.OK;
         MessageBox.Show("Mail sent", "", button, icon);
     }
     catch (Exception)
     {
         MessageBoxImage  icon   = MessageBoxImage.Error;
         MessageBoxButton button = MessageBoxButton.OK;
         MessageBox.Show("Mail didn't send", "", button, icon);
     }
 }
Exemplo n.º 8
0
        public async Task Smtp_SendTemplateMail_WithAttachments_ShouldSend()
        {
            SmtpCredentials credentials = new("smtp.mailtrap.io", "587", "false", "true", "d3538ae47a016d", "d4add3690c408c");

            byte[] txtBytes = File.ReadAllBytes("Attachments\\Attachment.txt");
            byte[] pdfBytes = File.ReadAllBytes("Attachments\\Attachment.pdf");

            List <Attachment> attachments = new()
            {
                new Attachment()
                {
                    ContentBytes = txtBytes, Name = "Attachment.txt"
                },
                new Attachment()
                {
                    ContentBytes = pdfBytes, Name = "Attachment.pdf"
                }
            };

            EmailComposer <TestMailModel> composer = new();
            EmailRequest <TestMailModel>  request  = composer
                                                     .SetModel(new TestMailModel {
                Email = "*****@*****.**", Name = "Guy Gadbois"
            })
                                                     .SetSubject("Hello world")
                                                     .SetFrom("*****@*****.**")
                                                     .SetTo("*****@*****.**")
                                                     .SetCc("*****@*****.**")
                                                     .SetBcc("*****@*****.**")
                                                     .Attach(attachments)
                                                     .Build();

            IMailer mailer = new SmtpMailer(credentials);

            IMailBodyBuilder builder          = new MailBodyBuilder();
            EmailRequest     populatedRequest = await builder
                                                .UseProvider(new AppDirectoryTemplateProvider("Templates", ".sbnhtml"))
                                                .UseResolver(new ViewModelTemplateResolver())
                                                .UseCompiler(new ScribanCompiler())
                                                .BuildAsync(request);

            await mailer.SendMailAsync(populatedRequest);
        }
    }
        public ActionResult SendQuery(string query, string email = null)
        {
            if (email == null)
            {
                ViewBag.Query = query;

                return(PartialView("SendQueryPartial"));
            }

            SmtpMailer.Instance(WebConfigurationManager.OpenWebConfiguration("~/web.config")).
            SendMail(email, "Query from QueryBuilder", query);

            if (System.Web.HttpContext.Current.Request.UrlReferrer != null)
            {
                return(Redirect(System.Web.HttpContext.Current.Request.UrlReferrer.ToString()));
            }

            return(RedirectToAction("List"));
        }
Exemplo n.º 10
0
        /// <summary>
        ///     Fired when an exception occurs.
        /// </summary>
        /// <param name="filterContext">The exception context.</param>
        public override void OnException(ExceptionContext filterContext)
        {
            // Get the exception
            var ex = filterContext.Exception;

            // Log it
            try
            {
                var mailer = new SmtpMailer();
                Task.Run(async() => await mailer.Send(_from, _to, string.Format(_subjectFormat, ex.GetType()), ex.ToString())).Wait();
            }
            catch
            {
                // Exception handler CANNOT raise an exception!
            }

            // Set exception handled
            filterContext.ExceptionHandled = true;
        }
        public ActionResult SendResultQuery(string email = null)
        {
            var dataTable = Session["datatableForGrid"] as DataTable;

            if (email == null || dataTable == null || dataTable.Rows.Count == 0)
            {
                return(PartialView("SendResultQueryPartial"));
            }
            var excelExporter = DataTableToExcelExporter.CreateInstance();
            var excelStream   = excelExporter.DataTableExportToMemory(dataTable, "Result query");

            SmtpMailer.Instance(WebConfigurationManager.OpenWebConfiguration("~/web.config")).
            SendMail(email, "Result query from QueryBuilder", "", excelStream);

            if (System.Web.HttpContext.Current.Request.UrlReferrer != null)
            {
                return(Redirect(System.Web.HttpContext.Current.Request.UrlReferrer.ToString()));
            }

            return(RedirectToAction("List"));
        }
Exemplo n.º 12
0
        /// <summary>
        /// The constructor.
        /// </summary>
        /// <param name="smtpMailer">The SMTP mailer to use.</param>
        /// <param name="from">The from email address.</param>
        /// <param name="to">The to email address.</param>
        /// <exception cref="System.ArgumentNullException">thrown when smtpMailer is null.</exception>
        /// <exception cref="System.ArgumentException">thrown when from or to is null, empty, or white space.</exception>
        public EmailErrorAttribute(SmtpMailer smtpMailer, string from, string to)
        {
            // Sanitize
            if (smtpMailer == null)
            {
                throw new ArgumentNullException("smtpMailer");
            }
            if (string.IsNullOrWhiteSpace(from))
            {
                throw new ArgumentException("cannot be null, empty, or white space", "from");
            }
            if (string.IsNullOrWhiteSpace(to))
            {
                throw new ArgumentException("cannot be null, empty, or white space", "to");
            }

            // Set fields
            _smtpMailer = smtpMailer;
            _from       = from;
            _to         = to;
        }
Exemplo n.º 13
0
        public IHttpActionResult SendMailSMTP(SendEmailRequest request)
        {
            try
            {
                request.ValidateNotNull();

                SmtpMailer sendMailSMTP = new SmtpMailer();
                sendMailSMTP.SendMail(request.ToEmails, request.Subject, request.Body, null,
                                      request.CcEmails, request.BccEmails, request.Attachments);

                return(Ok(new SendEmailResponse()
                {
                    Message = NotificationMessages.EmailMessageSent,
                    Success = Common.Enumerations.ResponseStatus.Succeeded
                }));
            }
            catch (NsiBaseException e)
            {
                return(BadRequest(e.Message));
            }
        }
        public ActionResult InviteUserToProjectPartial(UserViewModel user)
        {
            if (ModelState.IsValid)
            {
                var userForShared = _serviceUser.GetUserByID(user.UserId);

                var projectForShared = _serviceProject.GetProject(user.ProjectId);

                _currentUser = _serviceUser.GetUserByID(User.Identity.GetUserId());
                _serviceProjectsShareService.AddUserToProjectsShare(projectForShared, userForShared, UserRoleProjectsShareConstants.Invited, _currentUser);

                var bodyMail = _currentUser?.UserName + " invited you to a project!";
                SmtpMailer.Instance(WebConfigurationManager.OpenWebConfiguration("~/web.config")).SendMail(userForShared.Email, "Invitation to project", bodyMail);

                ViewBag.PreviousPage = System.Web.HttpContext.Current.Request.UrlReferrer;
                return(PartialView("Success"));
            }
            var users = _serviceProjectsShareService.GetUsersForSharedProject(_serviceProject.GetProject(user.ProjectId));

            user.Users = Mapper.Map <IEnumerable <ApplicationUser>, IEnumerable <UsersListViewModel> >(users);

            return(PartialView("InviteUserToProjectPartial", user));
        }
Exemplo n.º 15
0
        public User RegistrationUser(string firstName, string lastName, string email, string password)
        {
            SmtpMailer mailer = SmtpMailer.Instance();

            if (_userService.GetUserByEmail(email) == null)
            {
                User newUser = new User
                {
                    FirstName    = firstName,
                    LastName     = lastName,
                    Email        = email,
                    PasswordHash = Scrambler.GetPassHash(password)
                };

                _userService.CreateUser(newUser);
                mailer.SentRegisterNotification(email);

                MainWindowData.CurrentUser = newUser;

                return(newUser);
            }
            throw new CustomException(Resources.ExistEmailError);
        }