コード例 #1
0
        public async Task <IActionResult> AdicionarEmailAsync(Guid aggregateId, [FromBody] EmailDto dto)
        {
            await _pessoaService.AdicionarEmailAsync(aggregateId, dto.Endereco, dto.TipoId);

            await UnitOfWork.CommitAsyc();

            return(Ok(aggregateId));
        }
コード例 #2
0
        public async Task SubmitTicketAsync(UserAndOrganizationDto userAndOrganization, SupportDto support)
        {
            var currentApplicationUser = await _applicationUsers.SingleAsync(u => u.Id == userAndOrganization.UserId);

            var email = new EmailDto(currentApplicationUser.FullName, currentApplicationUser.Email, _applicationSettings.SupportEmail, $"{support.Type}: {support.Subject}", support.Message);

            await _mailingService.SendEmailAsync(email, true);
        }
コード例 #3
0
        public EmailResponseDto <string> SendMail(EmailDto emailInputs)
        {
            _logger.LogInformation("SendMail interactor method.");
            var response = new EmailResponseDto <string>();

            try
            {
                if (string.IsNullOrEmpty(emailInputs.ChannelKey))
                {
                    _logger.LogError("Channel key cannot be blank.");
                    response.Status  = false;
                    response.Message = "Channel key cannot be blank.";
                    return(response);
                }
                else
                {
                    var channelExist = _emailChannelInteractor.CheckIfChannelExist(emailInputs.ChannelKey).Result;
                    if (!channelExist)
                    {
                        _logger.LogError($"Invalid Channel key {emailInputs.ChannelKey}.");
                        response.Status  = channelExist;
                        response.Message = $"Invalid Channel key {emailInputs.ChannelKey}.";
                        return(response);
                    }
                }
                if (string.IsNullOrEmpty(emailInputs.TemplateName))
                {
                    _logger.LogError($"Template name cannot be blank.");
                    response.Status  = false;
                    response.Message = "Template name cannot be blank.";
                    return(response);
                }
                else
                {
                    var templateExist = _emailTemplateInteractor.CheckIfTemplateExist(emailInputs.ChannelKey, emailInputs.TemplateName).Result;
                    if (!templateExist)
                    {
                        _logger.LogError($"No template found for template name {emailInputs.TemplateName} and channel key {emailInputs.ChannelKey}.");
                        response.Status  = templateExist;
                        response.Message = $"No template found for template name {emailInputs.TemplateName} and channel key {emailInputs.ChannelKey}.";
                        return(response);
                    }
                }
                _logger.LogInformation("Trying to send Email.");
                _emailEventInteractor.SendMail(emailInputs);
                response.Status  = true;
                response.Message = $"Email is sent successfully to {string.Join(",", emailInputs.Recipients)}.";
                _logger.LogDebug("" + response.Message);
                return(response);
            }
            catch (Exception ex)
            {
                _logger.LogError("Error occurred in Email Interactor while sending email: ", ex.Message);
                response.Status  = false;
                response.Message = ex.Message;
                return(response);
            }
        }
コード例 #4
0
        ///<summary>Takes in CandidateInvitationID adn sends an email to the recruiter that has been assigned to this candidate </summary>
        /// <author>Drew Thomas</author>
        /// <date>6/18/2016</date>
        /// <exceptions></exceptions>
        /// <return></return>
        /// <param >candidateInvitationKey, currentUrl, controllersContext</param>
        /// <history>
        /// Date   Author    Change Reason     Change Description
        /// ----------------------------------------------------------------
        ///
        /// ----------------------------------------------------------------
        /// </history>
        public void EmailRecruiter(int candidateInvitiationKey, string currentUrl, RequestContext controllersContext)
        {
            //query that returns a emaildto form the candidateInvitiationsKey


            //All of the data below was created with a backend database

            /*var email = (
             *  from ci in Db.CandidateInvitations
             *  join cre in Db.CandidateResultEvaluations on ci.CandidateInvitationKey equals cre.CandidateInvitationKey
             *  join c in Db.Candidates on ci.CandidateKey equals c.CandidateKey
             *  join u in Db.Users on c.UserKey equals u.UserKey
             *  where ci.CandidateInvitationKey == candidateInvitiationKey
             */

            //select
            var email = new EmailDto
            {
                //CandidateID = ci.CandidateKey,
                // FirstName = c.FirstName,
                //LastName = c.LastName,
                //RecruiterID = c.UserKey.Value,
                //CandidateResultKey = cre.CandidateResultKey,
                //ToEmailAddress = u.EmailAddress

                CandidateID        = 1,
                FirstName          = "Jeffery",
                LastName           = "Thomas",
                RecruiterID        = 2,
                CandidateResultKey = 3,
                ToEmailAddress     = "*****@*****.**"
            };

            //).FirstOrDefault();

            currentUrl = "drewthomas.live";
            var urlSpec = "/thoughts-on-optimizing-for-an-event/";


            email.Link = GenerateRecruiterResultsLink(currentUrl, urlSpec);

            //setting the email properties
            var mailMessage = new MailMessage();

            mailMessage.Subject = email.CandidateFullName1 + ": Test Submission Confirmation";
            mailMessage.Body    = email.CandidateFullName1 + " has completed his/her evaluation test and this is the link to his/her results if you would like to view them: </br> </br> </br>"
                                  + email.Link;
            mailMessage.IsBodyHtml = true;

            mailMessage.To.Add(email.ToEmailAddress);

            //sending the email
            using (SmtpClient mailClient = new SmtpClient())
            {
                mailClient.Send(mailMessage);
                //Log.Debug("The email was successfuly sent to the Recruiter, letting them know that the candidate has finished their test");
            }
        }
コード例 #5
0
        private void SendEmail(string userEmail, IEnumerable <Post> wallPosts, string organizationShortName)
        {
            var messageBody    = GetMessageBody(wallPosts, organizationShortName);
            var messageSubject = ConstBusinessLayer.ShroomsInfoEmailSubject;

            var emailDTO = new EmailDto(userEmail, messageSubject, messageBody);

            _emailService.SendEmail(emailDTO);
        }
コード例 #6
0
        public async Task <IActionResult> RequestResetPassword([FromBody] EmailDto model)
        {
            if (ModelState.IsValid)
            {
                bool isEmail = Regex.IsMatch(model.Email, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase);

                if (isEmail)
                {
                    ApplicationUser user = await _userManager.FindByEmailAsync(model.Email).ConfigureAwait(false);

                    if (user != null)
                    {
                        // 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.GeneratePasswordResetTokenAsync(user).ConfigureAwait(false);

                        var callbackUrl = Url.Action("ResetPassword", "Account",
                                                     new { userId = user.Id, code },
                                                     protocol: HttpContext.Request.Scheme);

                        await _emailSender.SendEmailAsync(
                            user.Email,
                            "**Do Not Reply** NetAuthCore Password Reset Code",
                            "Your password reset code is: " + code + ". \n Please go to <a href=\"" + "https://localhost:4001/#/reset-password" + "\">NetCoreAuth</a> and reset your password").ConfigureAwait(false);

                        return(Ok(new RequestResult
                        {
                            State = RequestState.Success,
                            Msg = "Email sent for password reset request. Please check your email!"
                        }));
                    }


                    return(BadRequest(new RequestResult
                    {
                        State = RequestState.Failed,
                        Msg = "Error: Email not found!"
                    }));
                }
                else
                {
                    return(BadRequest(new RequestResult
                    {
                        State = RequestState.Failed,
                        Msg = "Error: Email not valid!"
                    }));
                }
            }
            else
            {
                return(BadRequest(new RequestResult
                {
                    State = RequestState.Failed,
                    Msg = "Error: " + string.Join(" ", ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage)),
                }));
            }
        }
コード例 #7
0
        public async Task VerifyGetEmail()
        {
            IEmailService testCandidate = CreateDefaultEmailService();

            EmailDto result = await testCandidate.GetEmail(1);

            Assert.NotNull(result);
            Assert.Equal(1, result.Id);
        }
コード例 #8
0
        public bool ValidateEmailDto(EmailDto emailDto)
        {
            if (string.IsNullOrEmpty(emailDto.Value))
            {
                return(false);
            }

            return(Regex.IsMatch(emailDto.Value, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"));
        }
コード例 #9
0
        public async Task <IActionResult> Put(int id, [FromBody] EmailDto emailDto)
        {
            if (id == 0 || emailDto.Id == 0)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, "Id needs to be greater than 0."));
            }

            return(await SaveAndReturnEntityAsync(async() => await _emailService.SaveAndReturnEntityAsync(emailDto)));
        }
コード例 #10
0
        public async Task <IActionResult> Post([FromBody] EmailDto emailDto)
        {
            if (emailDto.Id != 0)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, "Identity insert is not permitted."));
            }

            return(await SaveAndReturnEntityAsync(async() => await _emailService.SaveAndReturnEntityAsync(emailDto)));
        }
コード例 #11
0
ファイル: EmailController.cs プロジェクト: MarlomSouza/Email
        public void Post([FromBody] EmailDto emailDto)
        {
            var email   = _mapeadorDeEmail.Mapear(emailDto);
            var enviado = _enviadorDeEmail.Enviar(email);

            if (!enviado)
            {
                throw new Exception("Email não enviado");
            }
        }
コード例 #12
0
        public async Task <IActionResult> ChangeEmailStatusFromClose(string changeStatusData)
        {
            var emailDto = new EmailDto {
                GmailId = changeStatusData
            };

            await this.service.ChangeEmailStatusFromClose(emailDto);

            return(Json(new { changeStatus = changeStatusData }));
        }
コード例 #13
0
        public async Task SendAsync(EmailDto email)
        {
            MailMessage mail = EmailSetup(email);

            using SmtpClient smtp = new SmtpClient(_emailOptions.PrimaryDomain, _emailOptions.PrimaryPort);
            smtp.Credentials      = new NetworkCredential(_emailOptions.UsernameEmail, _emailOptions.UsernamePassword);
            smtp.EnableSsl        = true;

            await smtp.SendMailAsync(mail);
        }
コード例 #14
0
        public ActionResult <Email> sendEmail([FromBody] EmailDto email)
        {
            Email response = _userservice.SendEmail(email);

            if (response == null)
            {
                return(NotFound());
            }
            return(Ok(response));
        }
コード例 #15
0
        public void Create(Post post, HttpPostedFileBase upload, string precinctCode, string createdBy)
        {
            if (upload != null && upload.ContentLength > 0)
            {
                var image = new Asset
                {
                    AssetPath   = Guid.NewGuid() + Path.GetFileName(upload.FileName),
                    CreatedDate = DateTime.Now
                };

                string targetFolder = HttpContext.Current.Server.MapPath("~/Assets/PostImage/");
                string targetPath   = Path.Combine(targetFolder, image.AssetPath);
                upload.SaveAs(targetPath);
                post.PostImage = image;
            }

            if (post.IsEmail)
            {
                var userRepo             = new UserRepository();
                IEnumerable <User> users = new List <User>();

                if (!string.IsNullOrEmpty(precinctCode)) //if the post is for precinct, get users by PrecinctCode
                {
                    users = userRepo.GetUsersByGridding(precinctCode, post.LocationId, post.ZoneId, null);
                }
                else //get users based on Location or Zone
                {
                    users = userRepo.GetUsersByGridding(null, post.LocationId, post.ZoneId, null);
                }

                //filter out unsubscribed users
                users = users.Where(u => u.FFCommsOptOutStatus == false).ToList();

                Parallel.ForEach(users,
                                 user =>
                {
                    var email = new EmailDto
                    {
                        FirstName = user.FirstName,
                        LastName  = user.LastName,
                        Subject   = post.Title,
                        Body      = post.Body
                    };

                    EmailSender.SendEmail(email, user);
                });
            }

            post.CreatedDate   = DateTime.Now;
            post.CreatedByRole = createdBy;
            post.PublishDate   = post.PublishDate == null ? post.CreatedDate : post.PublishDate;

            db.Posts.Add(post);
            SaveChanges(db);
        }
コード例 #16
0
ファイル: EmailService.cs プロジェクト: JuanSGA24/Alejandria
        private string PopulateEmailBody(EmailDto emailView, string destinationUser)
        {
            var result        = string.Empty;
            var emailTemplate = GetEmailTemplateFromEmailType(emailView.EmailType);
            var body          = File.ReadAllText(GeFilePath(emailTemplate));

            switch (emailView.EmailType)
            {
            case EmailTypeEnum.Order:
                var menu = FormatMenuItems(emailView.DetailMenu);
                result = body.Replace("{0}", destinationUser);
                result = result.Replace("{1}", menu);
                result = result.Replace("{2}", emailView.Price.ToString());
                result = result.Replace("{3}", FormatButtonActions(emailView.ButtonActionList));

                //NotWorking :(
                //result = string.Format(body, destinationUser, menu,emailView.Price, FormatButtonActions(emailView.ButtonActionList));
                break;

            case EmailTypeEnum.CreateBooking:
                result = body.Replace("{0}", destinationUser);
                result = result.Replace("{1}", emailView.BookingDate.ToShortDateString());
                result = result.Replace("{2}", emailView.BookingDate.ToShortTimeString());
                result = result.Replace("{3}", emailView.Assistants.ToString());
                //notworking :(
                //result = string.Format(body, destinationUser, emailView.BookingDate.ToShortDateString() , emailView.BookingDate.ToShortTimeString(), emailView.Assistants.ToString());
                break;

            case EmailTypeEnum.InvitedGuest:

                result = body.Replace("{0}", destinationUser);
                result = result.Replace("{1}", $"{emailView.Host.Values.FirstOrDefault()} &lt;{emailView.Host.Keys.FirstOrDefault()}&gt; ");
                result = result.Replace("{2}", emailView.BookingDate.ToShortDateString());
                result = result.Replace("{3}", emailView.BookingDate.ToShortTimeString());
                result = result.Replace("{4}", FormatGuestList(emailView.EmailAndTokenTo));
                result = result.Replace("{5}", FormatButtonActions(emailView.ButtonActionList));


                //NotWorking :(
                //result = string.Format(body, destinationUser,$"{emailView.Host.Values.FirstOrDefault()} &lt;{emailView.Host.Keys.FirstOrDefault()}&gt; " ,emailView.BookingDate.ToShortDateString(), emailView.BookingDate.ToShortTimeString(), emailView.EmailAndTokenTo.Values, FormatButtonActions(emailView.ButtonActionList));
                break;

            case EmailTypeEnum.InvitedHost:
                result = body.Replace("{0}", destinationUser);
                result = result.Replace("{1}", emailView.BookingDate.ToShortDateString());
                result = result.Replace("{2}", emailView.BookingDate.ToShortTimeString());
                result = result.Replace("{3}", FormatGuestList(emailView.EmailAndTokenTo));
                result = result.Replace("{4}", FormatButtonActions(emailView.ButtonActionList));
                //NotWorking :(
                //result = string.Format(body, destinationUser, emailView.BookingDate.ToShortDateString(), emailView.BookingDate.ToShortTimeString(), emailView.Assistants, FormatButtonActions(emailView.ButtonActionList));
                break;
            }

            return(result);
        }
コード例 #17
0
 public static Email ToDocument(this EmailDto emailDto)
 {
     return(new Email
     {
         To = emailDto.To,
         Cc = emailDto.Cc,
         Subject = emailDto.Subject,
         Body = emailDto.Body,
         Id = emailDto.Id
     });
 }
コード例 #18
0
 public async Task <IActionResult> ValidateEmail([FromBody] EmailDto emailToTest)
 {
     if (await _repo.EmailExists(emailToTest.Email))
     {
         return(Ok(new { email_taken = true }));
     }
     else
     {
         return(Ok(new { email_taken = false }));
     }
 }
コード例 #19
0
        private async Task SendRegistrationEmail(string userEmail)
        {
            EmailDto email = new EmailDto()
            {
                To      = userEmail,
                Subject = "Cadastro de conta",
                Body    = "Obrigado por realizar o cadastro!"
            };

            await _emailService.SendAsync(email);
        }
コード例 #20
0
        public void SendEmailResetUser(EmailDto email)
        {
            MailMessage mail = new MailMessage();

            mail.To.Add(new MailAddress(email.Email, email.Name));
            mail.Subject    = "Portal de parceiro - redefinição de senha";
            mail.IsBodyHtml = true;
            mail.Body       = email.MessageReset;

            SendEmail(mail);
        }
コード例 #21
0
        private async Task SendInvitedGuestEmail(EmailDto dataToSend, InvitedGuest guest)
        {
            var url = Configuration["EmailServiceUrl"];

            var acceptUrl = string.Format(Configuration["AcceptBooking"], guest.GuestToken);
            var cancelUrl = string.Format(Configuration["CancelBooking"], guest.GuestToken);
            dataToSend.EmailType = EmailTypeEnum.InvitedGuest;
            dataToSend.ButtonActionList = new Dictionary<string, string> { { acceptUrl, "Accept" }, { cancelUrl, "Cancel" } };
            var mailService = new RestManagementService();
            await mailService.CallPostMethod(url, dataToSend);
        }
コード例 #22
0
        public async Task VerifyUpdateEmail(int id, EmailDto data, string expectedSubject, string expectedContent, List <string> expectedRecipients)
        {
            IEmailService testCandidate = CreateDefaultEmailService();

            EmailDto result = await testCandidate.UpdateEmail(id, data);

            Assert.Equal(expectedSubject, result.Subject);
            Assert.Equal(expectedContent, result.Content);
            Assert.Equal(expectedRecipients.Count, result.Recipients.Count);
            Assert.All(result.Recipients, s => Assert.Contains(s, expectedRecipients));
        }
コード例 #23
0
        public async Task VerifyPostEmail(EmailCreateableDto data, int expectedId, string expectedCreatedBy)
        {
            IEmailService testCandidate = CreateDefaultEmailService();

            EmailDto result = await testCandidate.PostEmail(data);

            Assert.NotNull(result);
            Assert.Equal(expectedId, result.Id);
            Assert.Equal(expectedCreatedBy, result.CreatedBy);
            Assert.Equal(1, DbContext.Recipients.Count(r => r.EmailId == result.Id));
        }
コード例 #24
0
        private async Task SendHostEmail(EmailDto dataToSend)
        {
            var url = Configuration["EmailServiceUrl"];
            var host = dataToSend.Host.FirstOrDefault();
            dataToSend.EmailAndTokenTo.Add(host.Value, host.Key);

            dataToSend.EmailType = EmailTypeEnum.InvitedHost;
            dataToSend.ButtonActionList = new Dictionary<string, string>();
            var mailService = new RestManagementService();
            await mailService.CallPostMethod(url, dataToSend);
        }
コード例 #25
0
        public void SendEmailNewUser(EmailDto email)
        {
            MailMessage mail = new MailMessage();

            mail.To.Add(new MailAddress(email.Email, email.Name));
            mail.Subject    = "Primeiro acesso ao portal de parceiros";
            mail.IsBodyHtml = true;
            mail.Body       = email.MessageCreat;

            SendEmail(mail);
        }
コード例 #26
0
        public async Task SendEmailAsync(string userId, string subject, string message)
        {
            var emailDto = new EmailDto
            {
                UserId       = userId,
                EmailSubject = subject,
                EmailBody    = message
            };

            await _httpClient.PostAsJsonAsync("api/users/SendEmail", emailDto);
        }
コード例 #27
0
        public IActionResult Create([FromBody] EmailDto emailDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var email = _emailLogic.Create(emailDto);

            return(CreatedAtAction(nameof(GetById), new { emailId = email.Id }, emailDto));
        }
        private async Task SendEmailsToAuthority(IEnumerable <string> emails, ApplicationDto applicationInfo, CancellationToken cancellationToken)
        {
            var content = await emailRendererService.RenderAuthorityContentAsync(applicationInfo, cancellationToken);

            var emailDto = new EmailDto()
            {
                EmailContent    = content,
                ToMailAddresses = emails.Select(e => new MailAddress(e)).ToList()
            };

            await smptService.SendEmailAsync(emailDto, cancellationToken);
        }
コード例 #29
0
        public async Task <IHttpActionResult> ForgotPassword(string email)
        {
            var baseUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority);

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await UserManager.FindByEmailAsync(email);

            if (user == null)
            {
                return(BadRequest("Email does not exist"));
            }
            else
            {
                try
                {
                    var userCode = userCodeService.FindByUser(user.Id);
                    if (userCode != null)
                    {
                        userCodeService.Delete(userCode.UserCodeK);
                    }

                    userCode = userCodeService.Create(new DataAccess.Models.UserCode()
                    {
                        UserK = user.Id
                    });
                    userCodeService.SaveChanges();
                    string code = userCode.Code;

                    var      adminSecurity = administrationSecurityService.GetAdministrationSecurity();
                    EmailDto emaildto      = new EmailDto()
                    {
                        EmailBody      = String.Format("This message was sent to you because someone requested a password reset on your account. <br/><br/>  Your Onetime code is: <b>{0}</b> <br/> This Onetime code is valid until: <b>{1}</b> at which time it will expire and a new one code will be required to be requested. <br/><br/> To enter your onetime code. Click on \"Forget my password\" then click on \"I have a onetime code\" <br/><br/>If you did not request this password reset, please ignore this message. <br/> Do not reply to this email message as the mail box is un-monitored.", code, userCode.ExpirationDateUtc.ToLocalTime().ToString("dd-MMMM-yyyy hh:mm tt")),
                        EmailSubject   = "SITETRAX Evolution password reset",
                        EmailSender    = "*****@*****.**",
                        EmailRecipient = user.Email
                    };

                    CustomEmail.SendPasswordEmail(adminSecurity.MailerServer, adminSecurity.MailerServerPort.Value, adminSecurity.MailerUsername, adminSecurity.MailerPassword, adminSecurity.PasswordResetEmail, user.Email, emaildto.EmailSubject, emaildto.EmailBody);
                }
                catch (Exception ex)
                {
                    var message = ex.Message;
                }

                //await UserManager.SendEmailAsync(user.Id, "Forgot Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
            }

            return(Ok());
        }
コード例 #30
0
        public void EmailDto_Extension_AsEntity_Null()
        {
            // Arrange
            EmailDto email = null;

            // Act
            var result = email.AsEntity();

            // Assert
            Assert.IsNull(result);
            Assert.AreEqual(null, result);
        }
コード例 #31
0
        public HttpResponseMessage SubscribeToNewsletter(EmailDto dto)
        {
            HostController.Instance.Update("NewsletterSubscribeEmail", dto.Email);

            return Request.CreateResponse(HttpStatusCode.OK, "Success");
        }
コード例 #32
0
ファイル: EmailManager.cs プロジェクト: ognjenm/egle
        /// <summary>
        /// Send a cancellation request email in regards to a cancel booking request
        /// </summary>
        /// <param name="requestCancelBooking">request information</param>
        /// <param name="booking">booking to request cancel for</param>
        /// <param name="order">order for booking</param>
        /// <returns>true if successful</returns>
        public bool SendCancellationRequestEmail(RequestCancelBooking requestCancelBooking, Model.Booking.Booking booking, Model.Order.Order order)
        {
            var business = businessDao.GetByKey(booking.BusinessId);
            var cultureInfo = PrepareCultureInfoUsage(order, business);
            var eviivoSupportEmail = GetEviivoEmailByType(InternalEmailAddressType.Support);

            var emailToSend = new EmailDto
                {
                    Priority = new EmailPriorityDto { Priority = EmailPriorityEnumDto.Normal },
                    User = GetEmailUser(),
                    SenderEmail = eviivoSupportEmail,
                    ReplyToEmail = eviivoSupportEmail,
                    Recipients = GetEviivoEmailsByType(GetInternalEmailAddressType(requestCancelBooking.CancellationRequestReason)),
                    Subject = GetCancellationRequestEmailSubject(requestCancelBooking, booking),
                    Bodies = GetCancellationRequestEmailBody(requestCancelBooking, order, booking, cultureInfo)
                };

            // add business as cc
            emailToSend.Recipients.Add(GetBusinessEmailForBooking(business));

            return SendEmailAction(emailToSend, CANCELLATION, booking.BookingReferenceNumber);
        }
コード例 #33
0
ファイル: EmailManager.cs プロジェクト: ognjenm/egle
        /// <summary>
        /// Send the email
        /// </summary>
        /// <param name="emailToSend">The email dto to send</param>
        /// <param name="emailType">The type of email to send</param>
        /// <param name="reference">The reference number</param>
        /// <param name="messageId">Email id</param>
        /// <returns>True if email was sent successfully</returns>
        private static bool SendEmailAction(
            EmailDto emailToSend,
            string emailType,
            string reference, out int messageId)
        {

            messageId = 0;

            if (IsDebugEnabled)
            {
                Logger.LogDebug("EmailManager: Sending {0} email - #{1}", emailType, reference);
            }

            //send the email here
            EmailResultDto emailResult = null;
            ServiceProxyManager.Execute<ServiceClient<IMailingService>, IMailingService>(proxy => emailResult = proxy.Proxy.SendEmail(emailToSend));

            // null implies communication or other related fault with email service
            // return true if successfully emailed
            var result = emailResult != null && emailResult.Status == EmailStatusEnumDto.Sent;

            if (!result)
            {
                Logger.LogError(Errors.SRVEX30109.GetDescription());
                Logger.LogError("Email result was:", emailResult);
            }
            else
            {
                messageId = emailResult.EmailId;

                if (IsDebugEnabled)
                {
                    Logger.LogDebug("EmailManager: {0} email sent - #{1}", emailType, reference);
                }
            }
            return result;
        }
コード例 #34
0
ファイル: EmailManager.cs プロジェクト: ognjenm/egle
        /// <summary>
        /// Send the email
        /// </summary>
        /// <param name="emailToSend">The email dto to send</param>
        /// <param name="emailType">The type of email to send</param>
        /// <param name="reference">The reference number</param>
        /// <returns>True if email was sent successfully</returns>
        private static bool SendEmailAction(
           EmailDto emailToSend,
           string emailType,
           string reference)
        {
            int messageId = 0;

            return SendEmailAction(emailToSend, emailType, reference, out messageId);
        }
コード例 #35
0
ファイル: EmailManager.cs プロジェクト: ognjenm/egle
        /// <summary>
        /// Prepare an email template and send the email based on user parameters and email template type
        /// </summary>
        /// <param name="linkUrl">The URL to use for the activation link</param>
        /// <param name="user">The user to get details from when populating template parameters</param>
        /// <param name="templateType">The template type</param>
        /// <returns>true if email was sent</returns>
        private bool SendEmailTemplate(string linkUrl, Model.User.User user, EmailTemplateTypeEnum templateType)
        {
            var emailToSend = new EmailDto();
            EmailResultDto emailResult = null;

            // change language for target user
            try
            {
                Activation.Culture = CultureInfo.GetCultureInfo(user.Extension.CultureCode);
                ResetPassword.Culture = CultureInfo.GetCultureInfo(user.Extension.CultureCode);
            }
            catch (CultureNotFoundException)
            {
                // Couldn't find the cultureFormat trying to be used, go with default
                Activation.Culture = CultureInfo.InvariantCulture;
                ResetPassword.Culture = CultureInfo.InvariantCulture;
            }
            linkUrl += "/?CultureCode=" + Activation.Culture;

            var emailSubject = string.Empty;
            var htmlEmailBody = string.Empty;
            switch (templateType)
            {
                case EmailTemplateTypeEnum.ActivationEmailTemplate:
                    emailSubject = Activation.Subject;
                    htmlEmailBody = GetActivationEmailBody(linkUrl);
                    break;
                case EmailTemplateTypeEnum.ResetPasswordEmailTemplate:
                    emailSubject = ResetPassword.Subject;
                    htmlEmailBody = GetResetPasswordEmailBody(linkUrl);
                    break;
            }

            emailToSend.Bodies = new List<EmailBodyDto>
            {
                new EmailBodyDto
                {
                    Content = htmlEmailBody,
                    MimeType = EmailMimeTypeEnumDto.Html
                }
            };

            emailToSend.Subject = emailSubject;
            emailToSend.SenderDisplayName = Activation.SenderDisplayName;
            emailToSend.SenderEmail = GetEviivoEmailByType(InternalEmailAddressType.Activations);
            emailToSend.ReplyToEmail = GetEviivoEmailByType(InternalEmailAddressType.Activations);
            emailToSend.Recipients = new List<EmailRecipientDto>
            {
                new EmailRecipientDto
                {
                    DisplayName = user.Extension.FirstName + " " + user.Extension.LastName,
                    Email = user.UserMembership.Email, 
                    RecipientType = new EmailRecipientTypeDto
                    {
                        RecipientType = EmailRecipientTypeEnumDto.To
                    }
                }
            };

            //set up user here based on token here
            var currentUser = Membership.GetUser(GetUserName());
            emailToSend.User = new UserDto
                {
                    UserId = currentUser != null && currentUser.ProviderUserKey != null ? (Guid)currentUser.ProviderUserKey : Guid.Empty,
                    ExternalUserSystem = EagleSystemName,
                    UserName = currentUser != null ? currentUser.UserName : string.Empty
                };

            emailToSend.Priority = new EmailPriorityDto { Priority = EmailPriorityEnumDto.Normal };

            if (IsDebugEnabled)
            {
                Logger.LogDebug("EmailManager: Sending {0} Email for User {1}", templateType.GetDescription(), user.UserName);
            }

            //send the email here
            ServiceProxyManager.Execute<ServiceClient<IMailingService>, IMailingService>(
                proxy => emailResult = proxy.Proxy.SendEmail(emailToSend));

            // null implies communication or other related fault with email service
            // return true if successfully emailed
            var result = !(emailResult == null ||
                (emailResult.Status == EmailStatusEnumDto.SendFailed ||
                emailResult.Status == EmailStatusEnumDto.Unknown ||
                emailResult.Status == EmailStatusEnumDto.Bounced));

            // if emailed record event for it
            if (result)
            {
                switch (templateType)
                {
                    case EmailTemplateTypeEnum.ResetPasswordEmailTemplate:
                        userManager.RecordUserEvent(user.UserName, UserEventTypesEnum.ReActivationEmailSent, reference: emailResult.EmailId.ToString(CultureInfo.InvariantCulture));
                        break;
                    case EmailTemplateTypeEnum.ActivationEmailTemplate:
                        userManager.RecordUserEvent(user.UserName, UserEventTypesEnum.ActivationEmailSent, reference: emailResult.EmailId.ToString(CultureInfo.InvariantCulture));
                        break;
                }
            }

            if (IsDebugEnabled)
            {
                Logger.LogDebug(!result ? string.Format("EmailManager: {0} for User {1}", Errors.SRVEX30109.GetDescription(), user.UserName) : string.Format("EmailManager: {0} Email sent for User {1}", templateType.GetDescription(), user.UserName));
            }

            return result;
        }
コード例 #36
0
ファイル: EmailManager.cs プロジェクト: ognjenm/egle
        /// <summary>
        /// Prepare an email template and send the email for commission changes
        /// </summary>
        /// <param name="businessChannelOverride">The business channel override</param>
        /// <param name="oldBusinessChannelOverride">The old business channel override</param>
        /// <returns>true if email was sent</returns>
        public bool SendCommissionUpdateEmail(BusinessChannelOverride businessChannelOverride, BusinessChannelOverride oldBusinessChannelOverride)
        {
            var commissionUpdateEmail = GetEviivoEmailByType(InternalEmailAddressType.CommissionUpdate);

            var emailToSend = new EmailDto
                {
                    Priority = new EmailPriorityDto { Priority = EmailPriorityEnumDto.Normal },
                    User = GetEmailUser(),
                    SenderEmail = commissionUpdateEmail,
                    ReplyToEmail = commissionUpdateEmail,
                    Recipients = GetEviivoEmailsByType(InternalEmailAddressType.Contracts),
                    Subject = string.Format(EmailTexts.Commission_Subject,
                                            oldBusinessChannelOverride.Business.ShortName,
                                            oldBusinessChannelOverride.Channel.ShortName)
                };

            var eviivoCommision = businessChannelOverride.EviivoCommission.HasValue ? businessChannelOverride.EviivoCommission.Value : 0;
            var distributorCommission = businessChannelOverride.DistributorCommission.HasValue ? businessChannelOverride.DistributorCommission.Value : 0;
            var oldEviivoCommision = oldBusinessChannelOverride.EviivoCommission.HasValue ? oldBusinessChannelOverride.EviivoCommission.Value : 0;
            var oldDistributorCommission = oldBusinessChannelOverride.DistributorCommission.HasValue ? oldBusinessChannelOverride.DistributorCommission.Value : 0;
            var commisionText = !businessChannelOverride.EviivoCommission.HasValue && !businessChannelOverride.DistributorCommission.HasValue ?
                                EmailTexts.DefaultChannelCommission : 
                                (eviivoCommision + distributorCommission).ToString("F");
            var oldCommisionText = !oldBusinessChannelOverride.EviivoCommission.HasValue && !oldBusinessChannelOverride.DistributorCommission.HasValue ?
                                    EmailTexts.DefaultChannelCommission :
                                    (oldEviivoCommision + oldDistributorCommission).ToString("F");
            var utcNow = DateTime.UtcNow;

            var parameters = new Dictionary<string, string>
                {
                    {LABEL_PROPERTY_NAME, EmailTexts.PropetyName},
                    {LABEL_CHANNEL_NAME, EmailTexts.ChannelShortName},
                    {LABEL_NEW_VALUE, EmailTexts.NewValue},
                    {LABEL_PREV_VALUE, EmailTexts.PrevValue},
                    {LABEL_COMMISSION, EmailTexts.Commission},
                    {LABEL_UPDATED_BY, EmailTexts.UpdatedBy},
                    {LABEL_UPDATED_AT, EmailTexts.UpdatedAt},
                    {LABEL_DISPLAYED_COMMISSION, EmailTexts.DisplayedCommission},
                    {BUSINESS_NAME, oldBusinessChannelOverride.Business.Name},
                    {CHANNEL_NAME, oldBusinessChannelOverride.Channel.ShortName},
                    {CHANNEL_OVERRIDE_UPDATED_BY, GetUserName()},
                    {CHANNEL_OVERRIDE_UPDATED_AT, string.Format("{0} {1}",utcNow.ToShortDateString(),utcNow.ToShortTimeString())},
                    {NEW_VALUE_COMMISSION, commisionText},
                    {NEW_VALUE_DISPLAYED_COMMISSION, businessChannelOverride.DisplayCommission ?? EmailTexts.DefaultChannelDisplay},
                    {PREV_VALUE_COMMISSION, oldCommisionText},
                    {PREV_VALUE_DISPLAYED_COMMISSION, oldBusinessChannelOverride.DisplayCommission ?? EmailTexts.DefaultChannelDisplay},
                };

            emailToSend.Bodies = new List<EmailBodyDto>
                {
                    new EmailBodyDto
                        {
                            Content = FormatTemplateLabels(HtmlTemplates.EmailTemplate_Commission, parameters),
                            MimeType = EmailMimeTypeEnumDto.Html
                        }
                };

            return SendEmailAction(emailToSend, COMMISSION, oldBusinessChannelOverride.Business.ShortName);
        }
コード例 #37
0
ファイル: EmailManager.cs プロジェクト: ognjenm/egle
        /// <summary>
        /// Send a confirmation email in regards to successful online bookings
        /// </summary>
        /// <param name="order">Order for the booking</param>
        /// <returns>True if successful</returns>
        public bool SendConfirmationEmails(Model.Order.Order order)
        {
            // validate the objects used in this method
            if (order == null || order.Bookings == null || !order.Bookings.Any())
            {
                return false;
            }

            // check first booking
            var firstBooking = order.Bookings.FirstOrDefault();
            if (firstBooking == null)
            {
                return false;
            }

            var businessId = firstBooking.BusinessId;
            var business = businessDao.GetByKey(businessId);
            // validate the business passed is valid
            if (business == null)
            {
                return false;
            }

            bool isOtaBooking;
            bool isMyWebOrWls;
            bool isCustomerRequested; 
            var propertyEmailSent = true;

            GetBookingEmailRequestSettings(order, out isOtaBooking, out isMyWebOrWls, out isCustomerRequested);            

            var cultureInfo = PrepareCultureInfoUsage(order, business, isOtaBooking);
            
            var emailToSend = new EmailDto
            {
                Priority = new EmailPriorityDto { Priority = EmailPriorityEnumDto.Normal },
                User = GetEmailUser(),
                SenderEmail = EmailTexts.ReservationConfirmation_SenderEmail,
                ReplyToEmail = business.Email,
                Subject = string.Format(EmailTexts.ReservationConfirmation_Subject, business.Name)
            };

            // we only want to send business copy if OTA, WLS or has been requested via the PMS
            if (isOtaBooking || isMyWebOrWls || isCustomerRequested)
            {
                var emailRecipients = new List<EmailRecipientDto>
                {
                    new EmailRecipientDto
                        {
                            Email = business.Email,
                            RecipientType = new EmailRecipientTypeDto { RecipientType = EmailRecipientTypeEnumDto.To }
                        }
                };
                var amount = firstBooking.Cost.HasValue ? firstBooking.Cost.Value : default(decimal);
                // set business recipient and body
                emailToSend.Recipients = emailRecipients;
                string startDate = firstBooking.EstimatedTimeOfArrival != null ? GetStartDate(firstBooking.EstimatedTimeOfArrival.ToString()) : firstBooking.StartDate.ToShortDateString();
                var total = string.Format("{0} {1}", order.CurrencySymbol, amount.ToString(COST_FORMAT, cultureInfo));
                string channelName = order.Channel != null ? string.Format("- {0}", order.Channel.Name) : string.Empty;
                emailToSend.Subject = string.Format(EmailTexts.ReservationConfirmation_SubjectProperty, firstBooking.Guest.Surname, startDate, total, firstBooking.RoomName, channelName);
                emailToSend.Bodies = GetReservationConfirmationEmailBody(business, order, cultureInfo, HtmlTemplates.EmailTemplate_PropertySingleBooking);
                propertyEmailSent = SendEmailAction(emailToSend, CONFIRMATION, order.OrderReference);
            }

            var guestEmailSent = true;

            // we only want to send customer copy if WLS or has been requested via the PMS
            if ((isMyWebOrWls || isCustomerRequested) && !string.IsNullOrWhiteSpace(order.LeadGuest.Email))
            {
                var emailRecipients = new List<EmailRecipientDto>
                    {
                        new EmailRecipientDto
                            {
                                DisplayName = order.LeadGuest.FormattedName,
                                Email = order.LeadGuest.Email,
                                RecipientType = new EmailRecipientTypeDto
                                    {
                                        RecipientType = EmailRecipientTypeEnumDto.To
                                    }
                            }
                    };

                // set customer recipient and body
                emailToSend.Recipients = emailRecipients;
                emailToSend.Bodies = GetReservationConfirmationEmailBody(business, order, cultureInfo, HtmlTemplates.EmailTemplate_GuestSingleBooking);
                emailToSend.Subject = string.Format(EmailTexts.ReservationConfirmation_Subject, business.Name);
                guestEmailSent = SendEmailAction(emailToSend, CONFIRMATION, order.OrderReference);
            }

            return propertyEmailSent && guestEmailSent;
        }
コード例 #38
0
ファイル: EmailManager.cs プロジェクト: ognjenm/egle
        /// <summary>
        /// Send cancellation emails
        /// </summary>
        /// <param name="order">Order for the booking</param>
        /// <returns>true if sending succeeds</returns>
        public bool SendCancellationEmails(Model.Order.Order order)
        {
            // validate the objects used in this method
            if (order == null || order.Bookings == null || !order.Bookings.Any())
            {
                return false;
            }

            // get first business for now
            var firstBooking = order.Bookings.FirstOrDefault();
            if (firstBooking == null)
            {
                return false;
            }

            var businessId = firstBooking.BusinessId;
            var business = businessDao.GetByKey(businessId);
            // validate the business passed is valid
            if (business == null)
            {
                return false;
            }

            var propertyEmailSent = true;

            var cultureInfo = PrepareCultureInfoUsage(order, business);

            var eviivoCancellationEmail = GetEviivoEmailByType(InternalEmailAddressType.Cancellations);

            var emailToSend = new EmailDto
            {
                SenderEmail = eviivoCancellationEmail,
                Priority = new EmailPriorityDto { Priority = EmailPriorityEnumDto.Normal },
                ReplyToEmail = eviivoCancellationEmail,
                User = GetEmailUser(),
                Subject = GetCancellationEmailSubject(business)
            };

            // if it is an OTA booking then we need to send a cancellation email to the business
            if (order.IsOTA)
            {
                var emailRecipients = new List<EmailRecipientDto>
                                          {
                                                new EmailRecipientDto
                                                    {
                                                        Email = business.Email,
                                                        RecipientType = new EmailRecipientTypeDto { RecipientType = EmailRecipientTypeEnumDto.To }
                                                    }                                              
                                          };

                // set business recipient and body
                emailToSend.Recipients = emailRecipients;
                string ChannelName;
                ChannelName = order.Channel != null ? string.Format("- {0}", order.Channel.Name) : string.Empty;
                emailToSend.Subject = string.Format(EmailTexts.CancellationConfirmation_CancelledProperty,firstBooking.Guest.Surname,firstBooking.StartDate.ToShortDateString(),firstBooking.RoomName,ChannelName);
                emailToSend.Bodies = GetCancellationConfirmationEmailBody(business, order, cultureInfo, HtmlTemplates.EmailTemplate_PropertySingleBooking);
                propertyEmailSent = SendEmailAction(emailToSend, CANCELLATION, order.OrderReference);                
            }

            var guestEmailSent = true;

            // if the SendCancellationEmail is true then send email to the customer - this will be false for OTA bookings as they handle cancellation emails
            if (firstBooking.CancellationDetails.SendCancellationEmail.HasValue && firstBooking.CancellationDetails.SendCancellationEmail.Value)
            {
                var emailRecipients = new List<EmailRecipientDto>
                                          {
                                              new EmailRecipientDto
                                                  {
                                                      Email = order.LeadGuest.Email,
                                                      DisplayName = order.LeadGuest.FormattedName,
                                                      RecipientType = new EmailRecipientTypeDto { RecipientType = EmailRecipientTypeEnumDto.To }
                                                  }
                                          };

                // set customer recipient and body
                emailToSend.Recipients = emailRecipients;
                emailToSend.Bodies = GetCancellationConfirmationEmailBody(business, order, cultureInfo, HtmlTemplates.EmailTemplate_GuestSingleBooking);
                emailToSend.Subject = GetCancellationEmailSubject(business);
                guestEmailSent = SendEmailAction(emailToSend, CANCELLATION, order.OrderReference);
            }

            return guestEmailSent && propertyEmailSent;
        }