Example #1
0
        public PartialViewResult Email(EmailViewModel model)
        {
            if (ModelState.IsValid)
            {
                var fullName = $"{model.FirstName} {model.LastName}".Trim();

                var message = new MessageRequest(Config.Email.TechnicalSupport)
                {
                    FromName = fullName,
                    FromAddress = model.Email,
                    Subject = model.Subject,
                    Message = model.Message
                };

                this.messageService.SendMessage(message);

                // send copy to user
                message = new MessageRequest(model.Email, fullName)
                {
                    FromAddress = "donotreply@" + Config.Website.DomainName,
                    Subject = $"Copy of message sent to {Config.Website.DomainName}: {message.Subject}"
                };

                this.messageService.SendMessage(message);

                return this.PartialView("email-confirm");
            }

            return this.PartialView();
        }
 public EmailFolderController(IShellService shellService, EmailLayoutViewModel emailLayoutViewModel, EmailListViewModel emailListViewModel, EmailViewModel emailViewModel)
 {
     this.shellService = shellService;
     this.emailLayoutViewModel = emailLayoutViewModel;
     this.emailListViewModel = emailListViewModel;
     this.emailViewModel = emailViewModel;
     this.deleteEmailCommand = new DelegateCommand(DeleteEmail, CanDeleteEmail);
 }
        public ActionResult Modify(int id, EmailViewModel emailViewmodel)
        {
            if (ModelState.IsValid)
            {
                emailViewmodel.EmailInstanceID = id;

                OperationContext.ServiceSession.EM_EmailInstancesService.Update(emailViewmodel.ToPOCO(), "SubjectLine", "EmailBody", "EnableTracking", "IsDraft", "Timespan", "AbsoluteDate", "UpdatedDate", "UpdatedBy");
                OperationContext.ServiceSession.SaveChange();
                return OperationContext.SendAjaxMessage(AjaxMessageStatus.OperationSuccess, "", "", null);
            }
            return OperationContext.SendAjaxMessage(AjaxMessageStatus.OperationFailed, "Please enable javascript in the browser", "", null);
        }
Example #4
0
        public void Init()
        {
            // arrange
            var eventAggregator = Mock.Create<IEventAggregator>(Behavior.Loose);
            var vm = new EmailViewModel { EventAggregator = eventAggregator };

            // act
            vm.Init(new RootStub());

            // assert
            Assert.AreEqual("This is action name", (string)vm.ActionList[0].Name);
            Assert.AreEqual("This is action subject", (string)vm.ActionList[0].SubjectTemplate.Template);
        }
 public ActionResult Add(EmailViewModel viewModel)
 {
     if (ModelState.IsValid)
     {
         OperationContext.ServiceSession.EM_EmailInstancesService.Add(viewModel.ToPOCO());
         OperationContext.ServiceSession.SaveChange();
         return OperationContext.SendAjaxMessage(AjaxMessageStatus.OperationSuccess, "", "", null);
     }
     else
     {
         return OperationContext.SendAjaxMessage(AjaxMessageStatus.OperationFailed, "Please enable javascript in browser.", "", null);
     }
 }
        public async Task <IActionResult> SendVerificationEmail(EmailViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(new BadRequestObjectResult("Модель данных некорректна"));
            }

            var user = await this.userManager.GetUserAsync(User);

            if (user == null)
            {
                return(new BadRequestObjectResult("Пользователь не найден"));
            }

            var code = await this.userManager.GenerateEmailConfirmationTokenAsync(user);

            var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
            var email       = user.Email;

            await this.emailSender.SendEmailConfirmationAsync(email, callbackUrl);

            return(new OkObjectResult("Письмо с подтверждением отправлено. Пожалуйста, проверьте вашу электронную почту."));
        }
Example #7
0
        private void SendMail(object value, string columnName, string Email, string Name)
        {
            try
            {
                var data   = Convert.ToString(value);
                var eModel = new EmailViewModel
                {
                    Subject = "BulkJobPost",
                    Body    = "Dear Admin," + "<br/><br/>" +
                              "An Employer " + Name + "(" + Email + ") was trying to add " + data + " as " +
                              columnName + ", which does not belong to our database.please do the needful.<br><br> Thank You <br>CareerIndeed Team",
                    To       = new string[] { config["AdminMail:Email"] },
                    From     = config["EmailCredential:Fromemail"],
                    IsHtml   = true,
                    MailType = (int)MailType.ForgotPassword
                };

                emailHandler.SendMail(eModel, -1);
            }
            catch (Exception ex)
            {
            }
        }
Example #8
0
        public void MissingTotal()
        {
            var value          = @"Hi Yvaine,
                        Please create an expense claim for the below. Relevant details are marked up as
                        requested…
                        <expense><cost_centre>DEV002</cost_centre>
                        <payment_method>personal card</payment_method>
                        </expense>
                        From: Ivan Castle
                        Sent: Friday, 16 February 2018 10:32 AM
                        To: Antoine Lloyd <*****@*****.**>
                        Subject: test
                        Hi Antoine,
                        Please create a reservation at the <vendor>Viaduct Steakhouse</vendor> our
                        <description>development team’s project end celebration dinner</description> on
                        <date>Tuesday 27 April 2017</date>. We expect to arrive around
                        7.15pm. Approximately 12 people but I’ll confirm exact numbers closer to the day.
                        Regards,
                        Ivan";
            var emailViewModel = new EmailViewModel(new EmailRepository());

            emailViewModel.ProcessingData(StringToXml.ToXml(value));
        }
        public async Task <ActionResult> UpdateEmailAddress(EmailViewModel model)
        {
            return(await Task.Run <ActionResult>(() =>
            {
                var response = _accountMediator.UpdateEmailAddress(UserContext.CandidateId, model);

                switch (response.Code)
                {
                case AccountMediatorCodes.UpdateEmailAddress.Ok:
                    SetUserMessage(response.Message.Text);
                    return RedirectToRoute(RouteNames.VerifyUpdatedEmail);

                case AccountMediatorCodes.UpdateEmailAddress.HasError:
                    SetUserMessage(response.Message.Text, response.Message.Level);
                    break;

                default:
                    throw new InvalidMediatorCodeException(response.Code);
                }

                return View(response.ViewModel);
            }));
        }
Example #10
0
        public ActionResult Save(Email email)
        {
            if (!ModelState.IsValid)
            {
                var vm = new EmailViewModel
                {
                    Email = email
                };
                TempData["error"] = "Something went wrong! Please try again later, or you can find me on multiple links below the 'SEND!' button!";
                return(RedirectToAction("Index", "Contact"));
            }

            if (email.Id == null || email.Id == 0)
            {
                email.Idopont     = DateTime.Now;
                email.Lattamozott = false;
                _context.Email.Add(email);
            }
            TempData["success"] = "Thank you for your time! You successfully sended your question!";

            _context.SaveChanges();
            return(RedirectToAction("Index", "Contact"));
        }
Example #11
0
 public void SendEmail(EmailViewModel model)
 {
     if (ModelState.IsValid)
     {
         var mail = new MailMessage();
         mail.To.Add("*****@*****.**");
         mail.From = new MailAddress(model.Email);
         mail.Subject = model.Name + " - " + model.Email + " - " + model.Subject;
         var Body = model.Message;
         mail.Body = Body;
         mail.IsBodyHtml = true;
         var smtp = new SmtpClient
         {
             Host = "smtp.gmail.com",
             Port = 587,
             UseDefaultCredentials = false,
             Credentials = new NetworkCredential
                 ("*****@*****.**", "finstrom1"),
             EnableSsl = true
         };
         smtp.Send(mail);
     }
 }
Example #12
0
        public async Task <ActionResult> SendAsync(EmailViewModel model)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.InvalidModelState(this.ModelState));
            }

            var meta = await AppUsers.GetCurrentAsync().ConfigureAwait(true);

            model.UserId = meta.UserId;

            try
            {
                bool result = await EmailMessages.SendAsync(this.Tenant, model).ConfigureAwait(true);

                return(this.Ok(result));
            }
            catch (Exception ex)
            {
                this.Failed(ex.Message, HttpStatusCode.InternalServerError);
                throw;
            }
        }
        public ActionResult RequestCode(int gameId)
        {
            var game = dbContext.Games.SingleOrDefault(g => g.Id == gameId);

            if (game == null)
            {
                return(new HttpNotFoundResult());
            }

            var code = GetCode(game);

            if (code == null)
            {
                return(View("CodeUnavailable"));
            }

            var viewModel = new EmailViewModel
            {
                RequestedGameId = gameId
            };

            return(View("EmailRequest", viewModel));
        }
Example #14
0
        public ActionResult Email(EmailViewModel model)
        {
            if (ModelState.IsValid)
            {
                var email = new Email()
                {
                    Company = model.Company,
                    Message = model.Message,
                    Name    = model.Name,
                    Phone   = model.Phone,
                    Subject = model.Subject,
                    Url     = model.Url
                };

                db.EmailRepo.Insert(email);
                db.SaveChanges();

                TempData["Success"] = "Message was sent successfully!";
                return(RedirectToAction("Email"));
            }

            return(View(model));
        }
Example #15
0
 public ActionResult Create([Bind(Include = "Name,PersonId")] EmailViewModel emailViewModel)
 {
     try
     {
         if (ModelState.IsValid)
         {
             _unitOfWork.EmailRepository.AddNewEmailToContact(new Email
             {
                 PersonId = emailViewModel.PersonId,
                 Name     = emailViewModel.Name
             });
             _unitOfWork.CommitChanges();
             TempData["SuccessMessage"] = "New email has been successfully added!";
             return(RedirectToAction("Edit", "Contacts", new { id = emailViewModel.PersonId }));
         }
         return(View(emailViewModel));
     }
     catch (Exception ex)
     {
         TempData["ErrorMessage"] = "An error occured while creating new email";
         return(View(emailViewModel));
     }
 }
Example #16
0
        public ActionResult SubmitForm(EmailViewModel model)
        {
            if (ModelState.IsValid)
            {
                //NOTE: Send confirmation email!!!

                var ptn_addr = model.Email_Address; // potential client address

                string tri_subject = "Project Information";
                string tri_body    = $"Brief description of potential project: \n{model.Description}\n\n" +
                                     $"Contact information: \n" +
                                     $"First Name: {model.First_Name}\n" +
                                     $"Last Name: {model.Last_Name}\n" +
                                     $"Email Address: {ptn_addr}";

                Email.Send(EmailInfo.User, tri_subject, tri_body); // Tridents copy

                string ptn_subject = "Trident Development - Project Details";
                string ptn_body    = $"Hello {model.First_Name} {model.Last_Name},\n\n" +
                                     $"We've received the information regarding your project.  Give us a couple days to get back to you." +
                                     $"If you'd like to get in contact with us personally you can reach Carlos at [email protected], " +
                                     $"Erick at [email protected], or Darryl at [email protected]" +
                                     $"Thank you for considering us!\n" + "-Team Trident\n\n" +
                                     $"This is an automatically generated email, DOT NOT REPLY";

                Email.Send(ptn_addr, ptn_subject, ptn_body); // prospect confirmation email

                EmailViewModel blank_model = new EmailViewModel {
                };
                return(View(blank_model));
            }

            else
            {
                return(View(model));
            }
        }
Example #17
0
 public ActionResult SendEmail(EmailViewModel model, int id)
 {
     if (ModelState.IsValid)
     {
         try
         {
             emails.SaveEmail(model, id);
             var         to          = contacts.GetContactById(id).Email;
             var         subject     = model.Subject;
             var         message     = model.Message;
             MailMessage mailMessage = new MailMessage();
             mailMessage.From = new MailAddress("*****@*****.**", "Natasha Dimova");
             mailMessage.To.Add(to);
             mailMessage.Subject    = subject;
             mailMessage.Body       = message;
             mailMessage.IsBodyHtml = false;
             //add host
             SmtpClient smtp = new SmtpClient("smtp.gmail.com");
             smtp.UseDefaultCredentials = true;
             smtp.Port        = 587;
             smtp.EnableSsl   = true;
             smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "*******");
             smtp.Send(mailMessage);
             ViewBag.Success = "";
             return(View());
         }
         catch (Exception ex)
         {
             return(View(ex.Message));
         }
     }
     else
     {
         ViewBag.Failed = "This action could not be completed. Try again!";
         return(View());
     }
 }
        public void ResetPassword(string token)
        {
            using (var ctx = new AyerLechonContext())
            {
                var tkn     = Guid.Parse(token);
                var account = ctx.Customers.FirstOrDefault(a => a.ResetPasswordToken == tkn);
                if (account == null)
                {
                    throw new ApplicationException("The token is expired. Please reset your password again.");
                }
                ctx.Customers.Attach(account);

                account.Password           = RandomString(6);
                account.ResetPasswordToken = null;
                account.LastChangePassword = DateTimeOffset.Now.ToEpochTime();

                var body = new StringBuilder();
                body.AppendFormat("<p>Dear {0}, </p>", account.FirstName + " " + account.LastName);
                body.Append("<p>The password has been reset.</p>");
                body.Append("<p>You can now log in with the following credentials:</p>");
                body.AppendFormat("<p>Username: {0}</p>", account.Email);
                body.AppendFormat("<p>New Password: {0}</p>", account.Password);
                body.Append("<br/><br/><p>Thanks, </p>");
                body.Append("<p>Ayer Lechon</p>");

                var emailModel = new EmailViewModel()
                {
                    Body    = body.ToString(),
                    EmailTo = account.Email,
                    Subject = "Your new password"
                };

                _emailService.Send(emailModel);

                ctx.SaveChanges();
            }
        }
        public async Task <ActionResult> Edit(int id, EmailViewModel systememail)
        {
            try
            {
                if (id <= 0)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
                }
                if (ModelState.IsValid)
                {
                    EmailTemplate emailTemplate = await _EmailTemplateQuery.GetAsync(id);

                    emailTemplate.Body = systememail.EmailText;
                    await _EmailTemplateCommand.UpdateAsync(emailTemplate);

                    await _EmailTemplateCommand.SaveChangesAsync();

                    TempData["MESSAGE"] = "Email Template " + emailTemplate.Name + " was successfully updated";
                    ModelState.Clear();
                    return(Json(new { success = true }));
                }
                else
                {
                    foreach (var modelError in ModelState.Values.SelectMany(modelState => modelState.Errors))
                    {
                        ModelState.AddModelError(string.Empty, modelError.ErrorMessage);
                    }
                    return(PartialView("_PartialAddEdit", systememail));
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, ex.Message);
                _log.Info(ex);
                return(View("Error"));
            }
        }
Example #20
0
 /// <summary>
 /// Signs in to user's gmail account.
 /// </summary>
 private void SignIn()
 {
     this.vm = new EmailViewModel(new EmailModel());
     if (ValidateAddress())
     {
         //email ends with "@gmail.com".
         vm.VM_EmailAddress = emailBox.Text;
         if (pwdBox.Password != "")
         {
             vm.VM_Password = pwdBox.Password;
             if (vm.SignIn())
             {
                 //show user's inbox
                 frame.Content = new InboxPage(this.vm, this.frame);
             }
             else
             {
                 Console.WriteLine("failed connection");
             }
         }
         else
         {
             MessageBox.Show("Fill in password",
                             "Empty Password detected",
                             MessageBoxButton.OK,
                             MessageBoxImage.Error);
         }
     }
     else
     {
         MessageBox.Show("Email address has to end with \"@gmail.com\" \nand contain at least 1 character" +
                         " before @gmail.com",
                         "Invalid Email Address",
                         MessageBoxButton.OK,
                         MessageBoxImage.Error);
     }
 }
        public IHttpActionResult ConfirmDepartmentCollection([FromBody] EmailViewModel viewModel)
        {
            var departmentId = viewModel.DepartmentId;

            // If Store clerk already confirmed
            var disbursementsConfirmedByStoreClerk = disbursementService
                                                     .getAllDisbursementsByStatusAndDepartmentId(CustomStatus.StoreConfirmedCollection, departmentId)
                                                     .ToList();

            foreach (var d in disbursementsConfirmedByStoreClerk)
            {
                var disbursement = disbursementService.Get(d.Id);
                disbursement.Status = CustomStatus.CollectionComplete;
                disbursementService.Save(disbursement);

                foreach (var id in d.ItemDisbursements)
                {
                    var inventoryItem = inventoryService.Get(id.ItemId);
                    inventoryItem.Quantity = inventoryItem.Quantity - id.AvailableQuantity;
                    inventoryService.Update(inventoryItem);
                }
            }

            // If Store clerk has not confirmed
            var disbursementsNotConfirmedByStoreClerk = disbursementService
                                                        .getAllDisbursementsByStatusAndDepartmentId(CustomStatus.ReadyForCollection, departmentId)
                                                        .ToList();

            foreach (var d in disbursementsNotConfirmedByStoreClerk)
            {
                var disbursement = disbursementService.Get(d.Id);
                disbursement.Status = CustomStatus.DepartmentConfirmedCollection;
                disbursementService.Save(disbursement);
            }

            return(Ok());
        }
Example #22
0
        public ActionResult NLog(EmailViewModel em)
        {
            if (!ModelState.IsValid)
            {
                this.ModelState.AddModelError("", "Fields are not valid");
            }
            string key = ConfigurationManager.AppSettings["Sendgrid.Key"];

            SendGridEmailService service = new SendGridEmailService(key);

            EmailMessage msg = new EmailMessage
            {
                Recipient = em.Email,
                Body      = em.Message,
                Subject   = em.Subject
            };

            var fileName = FileToByteArrayConverter.GetFilePath("Logs\\2018-05-21.log");
            var fileData = FileToByteArrayConverter.Convert(fileName);

            service.SendMail(msg, false, fileName, fileData);

            return(RedirectToAction("SuccessPage", "Home"));
        }
        public string SendEmailStandBy([FromBody] EmailViewModel emailViewModel)
        {
            string       result         = "Message Sent Successfully..!!";
            string       senderID       = "*****@*****.**";
            const string senderPassword = "******";

            try
            {
                SmtpClient smtp = new SmtpClient
                {
                    Host           = "smtp.zoho.com",
                    Port           = 587,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    Credentials    = new System.Net.NetworkCredential(senderID, senderPassword),
                    Timeout        = 30000,
                    EnableSsl      = true
                };

                string      body    = "<html><h1>Account activation</h1><body><p>Dear XXXX,</p><p> Your account [email protected] has been created by SKF Admin.</p><p> To complete registration, activate your account.</p><p> To activate your account, click the following link: <a>activate your account</a></p><p> Sincerely,</p><p>SKF eMaintenance Team</p></body></html>";
                MailMessage message = new MailMessage();
                message.From = new MailAddress(senderID);
                foreach (EmailAttributesViewModel eavm in emailViewModel.ToEmailList)
                {
                    message.To.Add(new MailAddress(eavm.EmailId, eavm.Name));
                }
                message.Subject    = "Activate your Account - Test";
                message.Body       = body;
                message.IsBodyHtml = true;
                smtp.Send(message);
            }
            catch (Exception ex)
            {
                result = "Error sending email.!!!";
            }
            return(result);
        }
Example #24
0
        public EmailViewModel GetByEmail(string email)
        {
            EmailViewModel model = null; //set it to null because we want an empty set to return if the id doesn't exist

            this.DataProvider.ExecuteCmd(
                //map parameters
                "Users_SelectByEmail", //store procedure

                inputParamMapper : delegate(SqlParameterCollection paramCol)
            {
                paramCol.AddWithValue("@Email", email);
            },
                //once executed by store procedure we get results back (singleRecordMapper)
                singleRecordMapper : delegate(IDataReader reader, short set)
            {
                model             = new EmailViewModel();
                int index         = 0;
                model.Id          = reader.GetSafeInt32(index++);
                model.Email       = reader.GetSafeString(index++);
                model.isConfirmed = reader.GetSafeBool(index++);
            }
                );
            return(model);
        }
Example #25
0
        public async Task <EmailViewModel> SendBulkEmailsAsync(EmailViewModel emailViewModel, EmailWrapperClient client, string username)
        {
            Response response;
            var      bulkContacts = GetBulkEmailContacts(emailViewModel);

            try
            {
                response = await client.SendMultipleEmailsAsync(bulkContacts, emailViewModel.EmailContact);

                if (IsResponseOk(response))
                {
                    //GetStatusNotification(EmailStatus.BulkEmailsDelivered);
                    emailViewModel.StatusNotification    = GetStatusNotification(EmailStatus.BulkEmailsDelivered);
                    emailViewModel.EmailContact.DateSent = DateTime.Now;
                    StoreBulkEmailContacts(bulkContacts, username);
                }
                else
                {
                    //GetStatusNotification(EmailStatus.BulkEmailsNotDelivered);
                    emailViewModel.StatusNotification = GetStatusNotification(EmailStatus.BulkEmailsNotDelivered);
                }
            }
            catch (Exception ex)
            {
                // log caught exception with Elmah
                ErrorSignal.FromCurrentContext().Raise(ex);

                emailViewModel.StatusNotification = GetStatusNotification(EmailStatus.BulkEmailsNotDelivered);
            }

            if (emailViewModel.StatusNotification != null)
            {
                emailViewModel.HasStatusNotification = true;
            }
            return(emailViewModel);
        }
Example #26
0
        /// <summary>
        ///     Renders the template for the email body to a string (~/Views/ScBooking/Email.cshtml)
        /// </summary>
        private async Task <string> GetEmailBody()
        {
            //user information
            SessionUserInfo user = _session.GetUserInformation();

            //booking information
            var booking = _session.ScBookingInfo;

            //set ViewModel for the email
            var viewModel = new EmailViewModel
            {
                EmailAddress        = user.Email,
                Phone               = user.Phone,
                CourtFileNumber     = _session.ScBookingInfo.CaseNumber,
                CaseLocationName    = booking.CaseLocationName,
                BookingLocationName = booking.BookingLocationName,
                TypeOfConference    = booking.HearingTypeName,
                Date = booking.DateFriendlyName,
                Time = booking.TimeSlotFriendlyName
            };

            //Render the email template
            string template = booking.HearingTypeId switch
            {
                //ScHearingType.AWS => "ScBooking/Email-CV-AWS",
                //ScHearingType.JMC => "ScBooking/Email-JMC",
                //ScHearingType.PTC => "ScBooking/Email-CV-PTC",
                //ScHearingType.TCH => "ScBooking/Email-CV-TCH",
                ScHearingType.TMC => "ScBooking/Email-TMC",
                ScHearingType.CPC => "ScBooking/Email-CPC",
                ScHearingType.JCC => "ScBooking/Email-JCC",
                _ => throw new ArgumentException("Invalid HearingTypeId"),
            };

            return(await _viewRenderService.RenderToStringAsync(template, viewModel));
        }
Example #27
0
        /// <summary>
        /// Konstruktor der eine E-Mail mit annimmt um die Daten dieser im Fenster zu setzen.
        /// Wird für Antworten und Weiterleiten genutzt.
        /// </summary>
        /// <param name="email"></param>
        public SendEmailWindow(EmailViewModel email) : this()
        {
            if (!String.IsNullOrEmpty(email.Sender))
            {
                // Anwortmail
                receiverTextBox.Text = email.Sender;
            }
            if (email.Receivers.Count > 0)
            {
                // alle Antworten
                receiverTextBox.Text += ", " + email.ReceiversString;
            }
            subjectTextBox.Text = email.Subject;
            messageTextBox.Text = email.Message;

            if (String.IsNullOrEmpty(email.Sender))
            {
                receiverTextBox.Focus();
            }
            else
            {
                messageTextBox.Focus();
            }
        }
Example #28
0
        private async Task SendEmail(EmailViewModel viewModel)
        {
            _logger.LogInformation($"CreateInvitationHandler : SendEmail : ViewModel: {JsonConvert.SerializeObject(viewModel)}");

            var tokens = GetTokens(viewModel);

            try
            {
                await _notificationApi.SendEmail(new Email()
                {
                    RecipientsAddress = viewModel.EmailAddress,
                    TemplateId        = viewModel.TemplateId.ToString(),
                    Tokens            = tokens,
                    SystemId          = "ApplyService",
                    ReplyToAddress    = "*****@*****.**",
                    Subject           = viewModel.Subject
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error sending email template ({viewModel.TemplateId}) to: '{viewModel.EmailAddress}'");
                throw;
            }
        }
        public async Task <IActionResult> ForgotPassword(EmailViewModel emailAddress)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(emailAddress.Email);

                if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    ModelState.AddModelError(string.Empty, "Email is not existed");
                    return(View());
                }

                // For more information on how to enable account confirmation and password reset please
                // visit https://go.microsoft.com/fwlink/?LinkID=532713
                var code = await _userManager.GeneratePasswordResetTokenAsync(user);

                var callbackUrl = Url.ResetPasswordCallbackLink(user.Id, code, Request.Scheme);
                await _emailSender.SendEmailResetPasswordAsync(emailAddress.Email, callbackUrl);

                return(View("ResetPasswordEmail"));
            }
            return(View());
        }
Example #30
0
        public void WhenAskedCanNavigateForSameQuery_ThenReturnsTrue()
        {
            var email = new EmailDocument();

            var emailServiceMock = new Mock <IEmailService>();

            emailServiceMock
            .Setup(svc => svc.GetEmailDocument(email.Id))
            .Returns(email)
            .Verifiable();

            var viewModel = new EmailViewModel(emailServiceMock.Object);

            NavigationContext context = new NavigationContext(new Mock <IRegionNavigationService>().Object, new Uri("location", UriKind.Relative));

            context.Parameters.Add("EmailId", email.Id);

            ((INavigationAware)viewModel).OnNavigatedTo(context);

            bool canNavigate =
                ((INavigationAware)viewModel).IsNavigationTarget(context);

            Assert.IsTrue(canNavigate);
        }
        //async void OnBackButtonClicked(object sender, EventArgs args)
        //{
        //    //await Navigation.PopModalAsync();
        //    await Navigation.PushAsync(new MyCamera());
        //    //Navigation.RemovePage(this);
        //}
        #endregion
        #region Send Email Code
        public void Sendmail(EmailViewModel emailviewmodel)
        {
            var ToAddress      = emailviewmodel.EmailAddress; //"*****@*****.**";
            var emailMessenger = CrossMessaging.Current.EmailMessenger;

            if (emailMessenger.CanSendEmail)
            {
                try
                {
                    string body  = string.Format("<html><head></head><body><p>First Name : {0}</p><p>Last Name : {1}</p><p>Email : {2}</p><p>Phone No : {3}</p><p>About Smile : {4}</p> </body></html>", emailviewmodel.FirstName, emailviewmodel.LastName, emailviewmodel.EmailAddress, emailviewmodel.Phone, emailviewmodel.About);
                    var    email = new EmailMessageBuilder().To(ToAddress)
                                   // .Bcc(new[] { "", "" })
                                   .Subject("Smile Dentistry")
                                   .BodyAsHtml(body)
                                   .WithAttachment(lblPath.Text, "Location of file")
                                   .Build();
                    emailMessenger.SendEmail(email);
                }
                catch (Exception ex)
                {
                    DisplayAlert("Error", "Error while Email send", "OK");
                }
            }
        }
Example #32
0
        public async Task <bool> Send(EmailViewModel email)
        {
            RestClient client = new RestClient();

            client.BaseUrl       = new Uri("https://api.mailgun.net/v3");
            client.Authenticator = new HttpBasicAuthenticator("api", _settings.MailgunApiKey);

            RestRequest request = new RestRequest();

            request.AddParameter("domain", _settings.MailgunDomainName, ParameterType.UrlSegment);
            request.Resource = "{domain}/messages";
            request.AddParameter("from", $"{_settings.SenderName} <{_settings.SenderAddress}>");

            foreach (var recipient in email.To.Split(','))
            {
                request.AddParameter("to", recipient);
            }

            request.AddParameter("subject", email.Subject);
            request.AddParameter("text", email.Text);
            request.Method = Method.POST;

            try
            {
                var response = await Task.Run(() => client.Execute(request));

                // TODO: need to log the error when the response status is not 200

                return(response.StatusCode == HttpStatusCode.OK);
            }
            catch (Exception ex)
            {
                // TODO: log the error message either physically or Azure table storage
                return(false);
            }
        }
Example #33
0
        public async Task <ActionResult> Detail(string mailId)
        {
            var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata(_authTokenService)).
                         AuthorizeAsync(CancellationToken.None);

            if (result.Credential == null)
            {
                return(new RedirectResult(result.RedirectUri));
            }
            else
            {
                var service = new GmailService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = result.Credential,
                    ApplicationName       = "Gmail webapp"
                });

                var getReq = service.Users.Messages.Get("me", mailId);
                getReq.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Full;
                Message message = getReq.ExecuteAsync().Result;

                return(View(EmailViewModel.FromEntity(GmailParser.FromGmailApi(message))));
            }
        }
Example #34
0
        public void SendEmail(EmailViewModel model)
        {
            var fromAddress = new MailAddress(Email, "CRM");
            var toAddress   = new MailAddress(model.To);

            var smtp = new SmtpClient
            {
                Host                  = "smtp.gmail.com",
                Port                  = 587,
                EnableSsl             = true,
                DeliveryMethod        = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials           = new NetworkCredential(Email, Password)
            };

            using (var message = new MailMessage(fromAddress, toAddress)
            {
                Subject = model.Subject,
                Body = model.Body
            })
            {
                smtp.Send(message);
            }
        }
        private void SendActivationMail(UserModel user)
        {
            string activationLink =
                $"{URLprotocol}://" +
                $"{_httpContextAccessor.HttpContext.Request.Host.Value}" +
                $"/Auth/EmailVerification?uId={user.UserId}&akey={user.ActivationKey}";

            var eModel = new EmailViewModel
            {
                Subject = "Account Activation Link",
                Body    = $"Dear {user.FirstName},<br/>Congrat's you have successfully registered with us." +
                          $"You are one step away to explore our application," +
                          $"Please <a href={activationLink}>click here</a> to activate your account." +
                          $"Your login details are below:<br/><br/>User Name:  {user.Email}<br/>Password: {user.Password} " +
                          $"<br/><br/>Thank You <br/> CareerIndeed Team",

                To       = new string[] { user.Email },
                From     = config["EmailCredential:Fromemail"],
                IsHtml   = true,
                MailType = (int)MailType.UserRegistrationActivationLink
            };

            emailHandler.SendMail(eModel, -1);
        }
Example #36
0
        public async Task <IActionResult> ForgotPassword(EmailViewModel emailViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View("ForgotPassword", emailViewModel));
            }

            DbUser user = await DbContext.Users.Where(s => s.Email == emailViewModel.Email).SingleOrDefaultAsync();

            if (user == null)
            {
                ModelState.AddModelError("", "Wrong email address");
                return(View("ForgotPassword", emailViewModel));
            }
            if (SendPasswordRecoveryEmail(user))
            {
                return(RedirectToAction("Login", "Auth"));
            }
            else
            {
                ModelState.AddModelError("", "Unable to send password recovery e-mail. ");
                return(View("ForgotPassword", emailViewModel));
            }
        }
Example #37
0
 public ActionResult Index()
 {
     var model = new EmailViewModel();
     return View(model);
 }
Example #38
0
        public void SelectedActionProperty()
        {
            // arrange
            const string Subject = "Test Subject";
            const string Message = "Test Message";
            const string Email1 = "*****@*****.**";
            const string Email2 = "*****@*****.**";
            const string Email3 = "*****@*****.**";
            var actionGuid = new Guid("EB8CCBA8-5903-4AB4-9CD4-192E7790B68D");

            var actionBuilder = new ApprovalActionDefinition.Builder
                                    {
                                        Guid = actionGuid,
                                        SubjectTemplate = new ActionSubjectTemplate("x"),
                                        MessageTemplate = new ActionMessageTemplate("y")
                                    };
            var selectedAction = actionBuilder.Build();
            var dynamicManagerMock = Mock.Create<IDynamicTypeManager>();
            var logger = Mock.Create<ILogger>(Behavior.Loose);
            var popupFactory = Mock.Create<PopupFactory>(Behavior.Loose);
            var windowManager = Mock.Create<IShell>(Behavior.Loose);

            var editableRoot = new RootStub { Id = 1, ProcessName = "AnyProcessName" };

            var command = Mock.Create<IGetActionInfoCommand>(Behavior.Loose);
            var commandResult = Mock.Create<IGetActionInfoResult>(Behavior.Loose);
            Mock.Arrange(() => commandResult.Subject).Returns(Subject);
            Mock.Arrange(() => commandResult.Message).Returns(Message);
            Mock.Arrange(() => commandResult.EmailList).Returns(new[] { Email1, Email2, Email3 });
            Mock.Arrange(() => command.ExecuteAsync(actionGuid, editableRoot)).Returns(TaskHelper.FromResult(commandResult));

            var eventAggregator = Mock.Create<IEventAggregator>(Behavior.Loose);

            var vm = new EmailViewModel
                         {
                             EventAggregator = eventAggregator,
                             DynamicManager = dynamicManagerMock,
                             Logger = logger,
                             ThePopupFactory = new Lazy<PopupFactory>(() => popupFactory),
                             WindowManager = new Lazy<IShell>(() => windowManager),
                             GetActionInfoCommand = command
                         };
            vm.Init(editableRoot);

            vm.SelectedAction = selectedAction;

            // assert
            Assert.AreEqual(Subject, vm.Subject);
            Assert.AreEqual(Message, vm.HtmlContent);

            // assert getter
            Assert.AreEqual(selectedAction, vm.SelectedAction);

            Mock.Assert(() => logger.Log(LogSeverity.Error, Arg.AnyString, Arg.IsAny<Exception>()), Occurs.Never());
            Mock.Assert(() => popupFactory.NotifyFailure(Arg.IsAny<Exception>(), Arg.AnyString, Arg.AnyBool), Occurs.Never());
        }
Example #39
0
        public void CancelEmailCommand()
        {
            // arrange
            var emailViewModel = new EmailViewModel();
            var mainViewModel = new MainViewModel();

            mainViewModel.Windows.Add(emailViewModel);
            emailViewModel.WindowManager = new Lazy<IShell>(() => mainViewModel);

            // act
            emailViewModel.CancelEmailCommand.Execute(null);

            // assert
            Assert.AreEqual(0, mainViewModel.Windows.Count);
        }
Example #40
0
        public void SendEmailCommand()
        {
            // test 1: if possible execute the command
            // arrange
            var eventAggregator = Mock.Create<IEventAggregator>(Behavior.Loose);
            var emailSettings = Mock.Create<IEmailSettings>(Behavior.Loose);
            Mock.Arrange(() => emailSettings.CanSendFromDetails).Returns(true);
            var emailViewModel = new EmailViewModel
                                     {
                                         EventAggregator = eventAggregator,
                                         EmailSettings = emailSettings,
                                         ReceiverCarbonCopyEmail = "*****@*****.**"
                                     };

            // assert
            Assert.IsTrue(emailViewModel.SendEmailCommand.CanExecute(null));

            // test 2. command body
            // mock returns the normal, working object
            // arrange
            var emailMock = Mock.Create<ISendEmailCommand>();
            Mock.Arrange(
                () => emailMock.BeginSendEmail(Arg.IsAny<string>(), Arg.IsAny<string>(), Arg.IsAny<string>(), Arg.IsAny<string>(), Arg.IsAny<IEnumerable<EmailLinkedResource>>(), Arg.IsAny<EventHandler<DataPortalResult<SendEmailCommand>>>()))
                .DoInstead<string, string, string, string, IEnumerable<EmailLinkedResource>, EventHandler<DataPortalResult<SendEmailCommand>>>(
                    (receiver, receiverCC, subject, message, linkedResources, callback) =>
                        {
                            var result = new DataPortalResult<SendEmailCommand>(new SendEmailCommand(), null, null);
                            callback(null, result);
                        });

            emailViewModel.SendEmailCslaCommand = emailMock;

            // when close window stub setup
            var windowManager = Mock.Create<IShell>();
            emailViewModel.WindowManager = new Lazy<IShell>(() => windowManager);

            // popup stub setup
            var popupMock = Mock.Create<PopupFactory>();
            Mock.Arrange(() => popupMock.NotifySuccess(Arg.IsAny<string>(), Arg.IsAny<string>()));
            emailViewModel.ThePopupFactory = new Lazy<PopupFactory>(() => popupMock);

            // dynamic type manager stub setup
            var type = new ReflectionStub().GetType();
            var dynamicManager = Mock.Create<IDynamicTypeManager>();
            Mock.Arrange(() => dynamicManager.GetCustomType(Arg.IsAny<string>(), "AuditLogCommand", false)).Returns(type);
            emailViewModel.DynamicManager = dynamicManager;

            // editable root stub setup
            emailViewModel.Init(new RootStub());

            // act
            emailViewModel.SendEmailCommand.Execute(null);

            // assert
            Mock.Assert(() => windowManager.CloseWindow(emailViewModel), Occurs.Once());
        }
Example #41
0
        public void SendEmailCommandException()
        {
            // arrange
            var eventAggregator = Mock.Create<IEventAggregator>(Behavior.Loose);
            var emailSettings = Mock.Create<IEmailSettings>(Behavior.Loose);
            Mock.Arrange(() => emailSettings.CanSendFromDetails).Returns(true);
            var vm = new EmailViewModel { EventAggregator = eventAggregator, EmailSettings = emailSettings, ReceiverCarbonCopyEmail = "*****@*****.**" };
            var emailMock = Mock.Create<ISendEmailCommand>();

            var popupFactory = Mock.Create<PopupFactory>(Behavior.CallOriginal);
            var notifyFailureWasCalled = false;
            Mock.Arrange(() => popupFactory.NotifyFailure(Arg.IsAny<Exception>(), "Popup_Error", false)).DoInstead(() => notifyFailureWasCalled = true);

            vm.ThePopupFactory = new Lazy<PopupFactory>(() => popupFactory);

            Mock.Arrange(() => emailMock.BeginSendEmail(Arg.AnyString, Arg.AnyString, Arg.AnyString, Arg.AnyString, Arg.IsAny<IEnumerable<EmailLinkedResource>>(), Arg.IsAny<EventHandler<DataPortalResult<SendEmailCommand>>>()))
                     .DoInstead<string, string, string, string, IEnumerable<EmailLinkedResource>, EventHandler<DataPortalResult<SendEmailCommand>>>(
                        (receiver, receiverCarbonCopyEmail, subject, message, linkedResources, callback) => 
                            callback(null, new DataPortalResult<SendEmailCommand>(null, new Exception(), null)));

            vm.SendEmailCslaCommand = emailMock;

            var logger = Mock.Create<ILogger>(Behavior.Loose);
            var wasLogged = false;
            Mock.Arrange(() => logger.Log(LogSeverity.Error, typeof(EmailViewModel).FullName, Arg.IsAny<Exception>())).DoInstead(() => wasLogged = true);

            vm.Logger = logger;

            // act
            vm.SendEmailCommand.Execute(null);

            // assert
            Assert.IsTrue(wasLogged);
            Assert.IsTrue(notifyFailureWasCalled);
        }
Example #42
0
        public void PropertiesTest()
        {
            var vm = new EmailViewModel();

            TestsHelper.TestPropertyWithNotifyPropertyChanged(vm, () => vm.ActionList);
            TestsHelper.TestPropertyWithNotifyPropertyChanged(vm, () => vm.Subject);
            TestsHelper.TestPropertyWithNotifyPropertyChanged(vm, () => vm.HtmlContent);
            TestsHelper.TestPropertyWithNotifyPropertyChanged(vm, () => vm.ReceiverEmail);
            TestsHelper.TestPropertyWithNotifyPropertyChanged(vm, () => vm.ReceiverCarbonCopyEmail);

            // arrange
            vm.ReceiverEmail = "*****@*****.**";
            vm.ReceiverCarbonCopyEmail = "*****@*****.**";

            // assert getter
            Assert.AreEqual("*****@*****.**", vm.ReceiverEmail);
            Assert.AreEqual("*****@*****.**", vm.ReceiverCarbonCopyEmail);
        }
        public EmailModule(IConnectionManager connectionManager)
            : base("email")
        {
            //Returns emails for your organization that are not processed
            Get["/"] = _ =>
            {
                if (!IsAuthenticated)
                {
                    return HttpStatusCode.Unauthorized;
                }
                var user =
                        DocumentSession.Load<EmailUser>(Principal.GetUserId());
                    var emails =
                        DocumentSession.Query<Email>()
                            .Where(e => e.Organization.Id == user.Organization.Id && e.Processed == false)
                            .Select(e => new EmailViewModel
                            {
                                Id = e.Id,
                                Body = e.Body,
                                Domain = e.Organization.Name,
                                From = e.From,
                                Subject = e.Subject,
                                To = e.To
                            });
                    return Response.AsJson(emails);
            };

            //Process an email
            Post["/process/{Id}"] = parameters =>
            {
                if (!IsAuthenticated)
                {
                    return HttpStatusCode.Unauthorized;
                }
                var user =
                        DocumentSession.Load<EmailUser>(Principal.GetUserId());

                    var email = DocumentSession.Load<Email>((Guid)parameters.Id);
                    //Verify the user is in the same orginazation as the email being processed.
                    if (email.Organization != user.Organization)
                        return HttpStatusCode.Unauthorized;
                    email.Processed = true;
                    var hub = connectionManager.GetHubContext<EmailHub>();
                    var emailViewModel = new EmailViewModel
                    {
                        Id = email.Id,
                        Body = email.Body,
                        Domain = email.Organization.Name,
                        From = email.From,
                        Subject = email.Subject,
                        To = email.To

                    };
                    hub.Clients.Group(emailViewModel.Domain).EmailRemoved(emailViewModel);
                    return HttpStatusCode.OK;
            };
            //Create an email.
            Post["/"] = _ =>
            {
                var email = this.Bind<EmailViewModel>();
                var organization = DocumentSession.Query<Organization>().Single(o => o.Name == email.Domain);
                var orgEmail = new Email
                {
                    Body = email.Body,
                    Create = DateTime.Now,
                    From = email.From,
                    Id = Guid.NewGuid(),
                    Organization = organization,
                    Subject = email.Subject,
                    To = email.To
                };
                DocumentSession.Store(orgEmail);
                var hub = connectionManager.GetHubContext<EmailHub>();
                email.Id = orgEmail.Id;
                hub.Clients.Group(organization.Name).AddEmail(email);
                return HttpStatusCode.OK;
            };
        }