コード例 #1
0
        public override async Task Submit(IContextLock access)
        {
            if (pairing.Type != PairingType.Manual)
            {
                throw new InvalidEnumArgumentException("CreateManualPairs: pairing");
            }

            using (var handle = await access.Write())
            {
                entries.Entry(pairing)
                .LoadRelations(p => p.Pairs)
                .LoadRelations(p => p.World.Members, m => m.Pairs1)
                .LoadRelations(p => p.World.Members, m => m.Pairs2)
                .LoadRelations(p => p.World.Pairs)
                .LoadRelations(p => p.World.BackupUser);

                foreach (var pair in pairing.Pairs)
                {
                    emails.Send(Emails.PairingReceiver, pair);
                    emails.Send(Emails.PairingInitiator, pair);
                }

                pairing.IsComplete = true;

                await handle.Finish();
            }
        }
コード例 #2
0
        private Boolean SendEmail(AspNetUser user, string message, string DestinationEmail, string channelId, string SenderEmail, LanguageCode culture, string RecipientName, string SenderName, List <email_attachment> attachmentList)
        {
            EmailProvider client = new EmailProvider(channelId);

            Dictionary <string, string> emailContents = new Dictionary <string, string>();

            emailContents.Add("TABLEBODY", message);
            emailContents.Add("from", SenderEmail);
            emailContents.Add("NAME", RecipientName);
            emailContents.Add("MEMBER", SenderName);
            //emailContents.Add("cc", SenderEmail);
            bool sent = false;

            if (attachmentList != null && attachmentList.ToList().Count > 0)
            {
                sent = client.Send(DestinationEmail, emailContents, client.GetTemplateType("CustomerOrder", culture), attachmentList);
            }
            else
            {
                sent = client.Send(DestinationEmail, emailContents, client.GetTemplateType("CustomerOrder", culture));
            }

            Logger.Info(String.Format("Sent {0}", sent));
            Logger.Info(String.Format("Email Sent to {0} with Email {1}", RecipientName, DestinationEmail));
            return(true);
        }
コード例 #3
0
        private void SendOrderToPrimaryEmail(AspNetUser user, string subject, string body, int caseId, string supplier, List <email_attachment> attachmentList, string channelId, int customerId, int deptId, ICollection <CustomerOrderAttachment> customer_Order_Attachment)
        {
            try
            {
                Logger.Info(String.Format("Email Sending to {0} with PrimaryEmail {1}", user.FirstName, user.Email));
                EmailProvider client = new EmailProvider(channelId);

                var cwaUrl = ConfigurationManager.AppSettings["ChannelOneLoginUrl"] + channelId;

                if (channelId == "12")
                {
                    cwaUrl = ConfigurationManager.AppSettings["ChannelTwoLoginUrl"] + channelId;
                }

                var emailContents = new Dictionary <string, string>();
                emailContents.Add("SUPPLIER", supplier);
                emailContents.Add("NAME", user.FirstName + " " + user.LastName);
                emailContents.Add("URL", cwaUrl);
                emailContents.Add("TABLEBODY", body);

                var type = client.GetTemplateType("OfferRequestOrder", user.LanguageCode, Convert.ToInt32(channelId));
                var slug = client.GetTemplateName(type);

                bool sent = false;
                if (attachmentList != null && attachmentList.ToList().Count > 0)
                {
                    sent = client.Send(user.Email, emailContents, type, attachmentList);
                }
                else
                {
                    sent = client.Send(user.Email, emailContents, type);
                }

                var mail = new MailMessage()
                {
                    CustomerId      = customerId,
                    DepartmentId    = deptId,
                    CauseTrackingId = caseId,
                    Kind            = MessageKind.Received,
                    ToAddress       = user.Email,
                    UserId          = user.Id,
                    HideFromUser    = true,
                    Tracking        = EntityTracker.StartTracking(ServiceId) // not directly by user, disputable
                };

                _mailMessageService.SaveMailMessage(mail, slug, channelId, emailContents);
                if (attachmentList != null && attachmentList.ToList().Count > 0)
                {
                    SaveCustomerAttachmentsInMailMessage(customer_Order_Attachment, mail.MessageId);
                }

                Logger.Info($"Email Sent to {user.FirstName} with PrimaryEmail {user.Email}");
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }
コード例 #4
0
        public void Send_sends_without_error()
        {
            var config   = this.AwsConfig;
            var provider = new EmailProvider(config);

            provider.Send("*****@*****.**", "Subject", "Body");
        }
コード例 #5
0
        public async Task <SendResponse> SendEmail(string to, string from, string subject, string htmlBody, List <IFormFile> attachments = null)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(to))
                {
                    throw new BadRequestException("", "Email of addressee is mandatory.");
                }
                if (string.IsNullOrWhiteSpace(subject))
                {
                    throw new BadRequestException("", "Subject is mandatory.");
                }

                var emailConfiguration = _configuration.FirstOrDefault(x => x?.Username?.ToLower() == from?.ToLower())
                                         ?? throw new BadRequestException("", "Provided email is not in configuration.");

                var provider = new EmailProvider(emailConfiguration);
                var result   = await provider.Send(to, subject, htmlBody, attachments);

                if (result.Exception != null)
                {
                    Log.Error(result.Exception, "Email automatic response could not be sended.");
                }

                return(result);
            }
            catch (Exception e)
            {
                return(new SendResponse(false, e));
            }
        }
コード例 #6
0
ファイル: EmailService.cs プロジェクト: ghjigan/Subtext
        public void EmailCommentToBlogAuthor(FeedbackItem comment)
        {
            if (String.IsNullOrEmpty(Blog.Email) ||
                comment.FeedbackType == FeedbackType.PingTrack ||
                Context.User.IsAdministrator())
            {
                return;
            }

            string fromEmail = comment.Email;

            if (String.IsNullOrEmpty(fromEmail))
            {
                fromEmail = null;
            }

            var commentForTemplate = new
            {
                blog    = Blog,
                comment = new
                {
                    author    = comment.Author,
                    title     = comment.Title,
                    source    = Url.FeedbackUrl(comment).ToFullyQualifiedUrl(Blog),
                    email     = fromEmail ?? "none given",
                    authorUrl = comment.SourceUrl,
                    ip        = comment.IpAddress,
                    // we're sending plain text email by default, but body includes <br />s for crlf
                    body =
                        (comment.Body ?? string.Empty).Replace("<br />", Environment.NewLine).Replace("&lt;br /&gt;",
                                                                                                      Environment.
                                                                                                      NewLine)
                },
                spamFlag = comment.FlaggedAsSpam ? "Spam Flagged " : ""
            };

            ITextTemplate template = TemplateEngine.GetTemplate("CommentReceived");
            string        message  = template.Format(commentForTemplate);
            string        subject  = String.Format(CultureInfo.InvariantCulture, Resources.Email_CommentVia, comment.Title,
                                                   Blog.Title);

            if (comment.FlaggedAsSpam)
            {
                subject = "[SPAM Flagged] " + subject;
            }
            string from = EmailProvider.UseCommentersEmailAsFromAddress
                              ? (fromEmail ?? EmailProvider.AdminEmail)
                              : EmailProvider.AdminEmail;

            EmailProvider.Send(Blog.Email, from, subject, message);
        }
コード例 #7
0
        /// <summary>
        /// Sends an email.
        /// </summary>
        /// <param name="to"></param>
        /// <param name="from"></param>
        /// <param name="subject"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override void Send(string to, string from, string subject, string message)
        {
            To      = to;
            From    = from;
            Subject = subject;
            Message = message;

            if (internalProvider == null)
            {
                return;
            }

            internalProvider.Send(to, from, subject, message);
        }
コード例 #8
0
        public void SendIsCalledIfEmailIsValid()
        {
            var     mockSender = new FakeEmailSender();
            var     sut        = new EmailProvider(emailSender: mockSender);
            dynamic testEmail  = new ExpandoObject();

            testEmail.From    = "*****@*****.**";
            testEmail.To      = "*****@*****.**";
            testEmail.Subject = "NADA";
            testEmail.Body    = "No Body";

            sut.Send(testEmail);

            Assert.That(mockSender.SendWasCalled, Is.True);
        }
コード例 #9
0
        public IActionResult CreateReset([FromBody] LoginCredentials creds, [FromServices] EmailProvider email)
        {
            if (accounts.Include(a => a.ResetToken).Find(new EmailAddress(creds.Email), out var account))
            {
                account.ResetToken = new ResetToken();
                account.ResetToken.CreateIds();
                account.ResetToken.Expiration = DateTime.UtcNow.AddHours(24);

                accounts.Update(account);

                email.Send(Emails.PasswordReset, account);
            }

            return(Ok());
        }
コード例 #10
0
        public void FailureToSendThrowsException()
        {
            var mockSender = new FakeEmailSender();

            mockSender.WillFail = true;

            var     sut       = new EmailProvider(emailSender: mockSender);
            dynamic testEmail = new ExpandoObject();

            testEmail.From    = "*****@*****.**";
            testEmail.To      = "*****@*****.**";
            testEmail.Subject = "NADA";
            testEmail.Body    = "No Body";

            Assert.Throws <EmailException>(() => sut.Send(testEmail));
        }
コード例 #11
0
        public IActionResult SendEmails(Guid?accountId, Guid identifier, string type, [FromServices] EmailProvider emails)
        {
            if (!worlds.Include(w => w.Members).Find(identifier, out var world))
            {
                return(NotFound());
            }

            if (!Permissions.ModifyWorld(world))
            {
                return(NotFound());
            }

            if (accountId.HasValue && world.Account.Guid != accountId.Value)
            {
                return(NotFound());
            }

            var members = worlds.Members(world);

            switch (type)
            {
            case "confirmation":
                var unconfirmed = members.All
                                  .Where(u => !u.HasEmailValidation);

                foreach (var member in unconfirmed)
                {
                    emails.Send(Emails.JoinConfirmation, member);
                }

                break;

            default:
                return(NotFound());
            }

            return(Ok());
        }
コード例 #12
0
 public ActionResult Resend(InvitationViewModel model)
 {
     try
     {
         using (var db = new ApplicationDbContext())
         {
             var result = db.Invitations.Where(x => x.Email == model.Email && x.TemplateId == model.NoticeId && x.EmailTemplate.OrgId == IMSUserUtil.OrgId).SingleOrDefault();
             if (result == null)
             {
                 throw new Exception("Not found");
             }
             EmailProvider.Send(result.Subject, model.Email, result.Content, IMSEnvProperties.GmailAccount, IMSEnvProperties.GmailAppPassword);
             return(Json(new ImsResult {
             }));
         }
     }
     catch (Exception e)
     {
         return(Json(new ImsResult {
             Error = e.Message
         }));
     }
 }
コード例 #13
0
        public override async Task Submit(IContextLock access)
        {
            using (var handle = await access.Write())
            {
                var repo = pairings.Pairs(pairing);

                foreach (var pair in pairs)
                {
                    pair.Outcome = PairOutcome.Unknown;

                    repo.Add(pair);

                    emails.Send(Emails.PairingReceiver, pair);
                    emails.Send(Emails.PairingInitiator, pair);
                }

                foreach (var member in optOuts)
                {
                    member.OptOut = false;

                    emails.Send(Emails.OptOut, member);
                }

                if (unpaired != null)
                {
                    if (pairing.World.BackupUser != null)
                    {
                        emails.Send(Emails.PairingInitiator, unpaired, pairing.World.BackupUser);
                        emails.Send(Emails.PairingReceiver, unpaired, pairing.World.BackupUser);
                    }
                    else
                    {
                        emails.Send(Emails.UnpairedMember, unpaired);
                    }
                }

                pairing.IsComplete = true;

                await handle.Finish();
            }
        }
コード例 #14
0
        public ActionResult Send(InvitationBatchViewModel model)
        {
            try
            {
                StringBuilder smtpError = new StringBuilder();
                if (!ModelState.IsValid)
                {
                    throw new Exception("Invalid Input!");
                }
                //To check the placeholder for the invitation link.
                if (!model.Content.Contains(IMSContants.INVITATION_CODE_PLACEHOLER))
                {
                    throw new Exception("Invitation Code Placeholder is missing!");
                }

                var invitationQueue = new List <Invitation>();
                RecruitStatusType recruitStatusType;
                using (var db = new ApplicationDbContext())
                {
                    var template = db.Templates.Where(x => x.Id == model.NoticeId && x.IsActive && x.OrgId == IMSUserUtil.OrgId && x.TemplateType.Code == (int)TemplateTypeCode.Email).SingleOrDefault();
                    if (template == null)
                    {
                        throw new Exception("Invalid Notice");
                    }
                    //To prevent sending a duplicate invitation.
                    var duplicates = db.Invitations.Where(x => x.TemplateId == model.NoticeId && model.Emails.Contains(x.Email)).ToList();
                    if (duplicates.Count() > 0)
                    {
                        throw new Exception(string.Format("Duplicated request: {0}", string.Join(", ", duplicates.Select(x => x.Email).ToArray())));
                    }
                    recruitStatusType = db.RecruitStatusType.Where(x => x.Code == (int)RecruitStatusCode.InvitationSent).Single();
                }

                //To avoid holding db resource too long, make the following smtp job done separately.
                //After finishing smtp job, get db connection to save the record.
                foreach (var email in model.Emails.Distinct())
                {
                    try {
                        var invitationCode = Convert.ToBase64String(Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()));
                        var link           = string.Format("<a href='{0}?invitationCode={1}'>{0}?invitationCode={1}</a>", IMSEnvProperties.ContractEndPoint, invitationCode);
                        var html           = model.Content.Replace(IMSContants.INVITATION_CODE_PLACEHOLER, link);
                        EmailProvider.Send(model.Subject, email, html, IMSEnvProperties.GmailAccount, IMSEnvProperties.GmailAppPassword);
                        var invitation = new Invitation
                        {
                            TemplateId          = model.NoticeId,
                            Email               = email,
                            Subject             = model.Subject,
                            Content             = html,
                            RecruitStatusTypeId = recruitStatusType.Id,
                            InvitationCode      = invitationCode,
                            SentAt              = DateTime.UtcNow,
                            CreatedById         = IMSUserUtil.Id,
                            CreatedAt           = DateTime.UtcNow,
                            UpdatedById         = IMSUserUtil.Id,
                            UpdatedAt           = DateTime.UtcNow
                        };
                        invitationQueue.Add(invitation);
                    } catch
                    {
                        smtpError.Append(string.Format(" {0} ", email));
                    }
                }
                //Save the log only for successful invitation.
                //Return the list of failed invitation as an error message.
                using (var db = new ApplicationDbContext())
                {
                    db.Invitations.AddRange(invitationQueue);
                    db.SaveChanges();
                }
                if (smtpError.Length > 0)
                {
                    throw new Exception(string.Format("SMTP Error:{0}", smtpError.ToString()));
                }
                return(Json(new ImsResult {
                }));
            }
            catch (Exception e) { return(Json(new ImsResult {
                    Error = e.Message
                })); }
        }
コード例 #15
0
 protected override async Task Send(NotificationMessage model, EmailNotificationSettings settings)
 {
     await EmailProvider.Send(model, settings);
 }
コード例 #16
0
        public ActionResult ApproveApplicant(string email, int templateId)
        {
            try
            {
                using (var db = new ApplicationDbContext())
                {
                    var  userManager = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>();
                    var  applicant   = db.Applicants.Where(x => x.Email == email && x.TemplateId == templateId).Include(x => x.Invitation).Single();
                    User user        = userManager.FindByEmail(email);

                    //check if the user account already exist
                    if (user == null)
                    {
                        string role;
                        role = "intern";



                        //generate random password
                        var    password = System.Web.Security.Membership.GeneratePassword(6, 0);
                        Random rnd      = new Random();
                        password = Regex.Replace(password, @"[^a-zA-Z0-9]", m => rnd.Next(0, 10).ToString());


                        // use identity to create new user
                        userManager.Create(new User
                        {
                            UserName  = email,
                            Email     = email,
                            OrgId     = IMSUserUtil.OrgId,
                            FirstName = applicant.Firstname,
                            LastName  = applicant.Lastname
                        }, password);

                        //get the created user
                        user = userManager.FindByName(email);
                        //add role(intern) to the user above
                        userManager.AddToRole(user.Id, role);

                        //add new internship related to the new user
                        var userId     = user.Id;
                        var commenceAt = DateTime.Now.Date.ToUniversalTime();
                        var expiryAt   = DateTime.UtcNow.AddDays(90 + 1).Date.ToUniversalTime();
                        var intern     = db.Users.Where(x => x.Id == userId).Single();
                        var internship = new Internship {
                            Id         = userId,
                            CommenceAt = commenceAt,
                            ExpiryAt   = expiryAt,
                            Intern     = intern
                        };


                        db.Internships.Add(internship);

                        //update the applicant status to approved
                        var statusApproved = db.RecruitStatusType.Where(x => x.Code == (int)RecruitStatusCode.Approved).Single();

                        var invitation = db.Invitations.Where(x => x.InvitationCode == applicant.Invitation.InvitationCode && x.RecruitStatusType.Code == (int)RecruitStatusCode.ContractReceived).Single();
                        invitation.RecruitStatusType = statusApproved;



                        //save all changes to database
                        db.SaveChanges();

                        //send account details email to user
                        String subject = "IMS Login Account Details";
                        String content = "Your login user name: " + email + "." + "\r\n" + "Your password: "******"." + "\r\n" + "You can change your password after you logged in IMS. Thank you.";
                        EmailProvider.Send(subject, email, content, IMSEnvProperties.GmailAccount, IMSEnvProperties.GmailAppPassword);

                        //result message  shown in the front end
                        ViewBag.msg = "Create account successful and notification sent to the applicant.";
                        return(PartialView());
                    }
                    else
                    {
                        //update the old account with new info
                        user.FirstName = applicant.Firstname;
                        user.LastName  = applicant.Lastname;
                        user.OrgId     = IMSUserUtil.OrgId;
                        userManager.Update(user);
                        var internship = db.Internships.Where(x => x.Id == user.Id).Single();
                        internship.CommenceAt = DateTime.UtcNow;
                        internship.ExpiryAt   = DateTime.UtcNow.AddDays(90);


                        //update the applicant status to approved
                        var statusApproved = db.RecruitStatusType.Where(x => x.Code == (int)RecruitStatusCode.Approved).Single();
                        var invitation     = db.Invitations.Where(x => x.InvitationCode == applicant.Invitation.InvitationCode && x.RecruitStatusType.Code == (int)RecruitStatusCode.ContractReceived).Single();
                        invitation.RecruitStatusType = statusApproved;


                        //save all changes to database
                        db.SaveChanges();

                        //result message  shown in the front end
                        ViewBag.msg = "Account existed before and updated now.";
                        return(PartialView());
                    }
                }
            }
            catch (Exception e)
            {
                ViewBag.msg = e.ToString();
                return(PartialView());
            }
        }
コード例 #17
0
        public IActionResult CreateMembers(Guid worldId, [FromQuery] bool confirm, [FromBody] List <Member> body)
        {
            var value = worlds
                        .Include(w => w.Account)
                        .Find(worldId);

            if (!value.Exists(out var world))
            {
                return(NotFound());
            }

            var members = worlds.Members(world);

            var isConfirmed = true;

            if (Auth == null || !Permissions.ModifyWorld(world))
            {
                if (world.Privacy == WorldPrivacy.InviteOnly)
                {
                    return(Unauthorized());
                }

                if (world.Privacy == WorldPrivacy.VerificationRequired)
                {
                    isConfirmed = false;
                }

                confirm = true;
            }

            var list = new List <Member>();

            foreach (var id in body)
            {
                id.FirstName = id.FirstName.Trim();
                id.LastName  = id.LastName.Trim();
                id.Email     = id.Email.Trim();

                var isNew = false;
                if (!members.Find(id.Email, out var member))
                {
                    member = new Member();
                    isNew  = true;
                }

                member.FirstName = id.FirstName;
                member.LastName  = id.LastName;
                member.Email     = id.Email;

                member.JoinToken  = Database.Token.Generate();
                member.LeaveToken = Database.Token.Generate();

                if (isNew)
                {
                    members.Add(member);
                }
                else
                {
                    members.Update(member);
                }

                list.Add(member);

                switch (world.Account.Type)
                {
                case AccountType.Standard:
                    member.HasLeft              = false;
                    member.HasEmailValidation   = !confirm;
                    member.HasPrivacyValidation = isConfirmed;

                    if (Auth == null)
                    {
                        emails.Send(Emails.JoinConfirmation, member);
                    }
                    else
                    {
                        emails.Send(Emails.MemberAdded, member);
                    }
                    break;

                case AccountType.Research:
                    member.HasLeft              = false;
                    member.HasEmailValidation   = true;
                    member.HasPrivacyValidation = true;
                    break;
                }
            }

            return(Ok(list));
        }
コード例 #18
0
        public IActionResult CreateAccount([FromBody] Account account)
        {
            if (!Permissions.CreateAccount())
            {
                return(Unauthorized());
            }

            if (account.Type == AccountType.ERROR)
            {
                return(BadRequest());
            }

            bool isCreating;

            account.Email = new EmailAddress(account.Email.Value.Trim());

            if (accounts.Find(account.Email, out var old))
            {
                if (old.Status != AccountStatus.Deleted)
                {
                    return(BadRequest());
                }

                old.Name   = account.Name;
                account    = old;
                isCreating = false;
            }
            else
            {
                isCreating = true;
            }

            account.Status     = AccountStatus.New;
            account.ResetToken = null;

#if DEBUG
            if (account.Email.Value == "test-auto-email")
            {
                account.Credentials = new Credentials();
                account.Credentials.CreateIds();
                account.Credentials.Salt = crypto.GenerateSalt();
                account.Credentials.Hash = crypto.GenerateHash(account.Credentials.Salt, "test-auto-password");
            }
            else
            {
#endif
            var password = crypto.CreatePassword();

            account.Credentials = new Credentials();
            account.Credentials.CreateIds();
            account.Credentials.Salt = crypto.GenerateSalt();
            account.Credentials.Hash = crypto.GenerateHash(account.Credentials.Salt, password);

            emails.Send(Emails.AccountCreation, account, password);
#if DEBUG
        }
#endif

            if (isCreating)
            {
                accounts.Add(account);
            }
            else
            {
                accounts.Update(account);
            }

            return(Ok(account));
        }
コード例 #19
0
        /// <summary>
        ///     Registers a user and their associated registration into the database
        /// </summary>
        /// <param name="request">The fields used to populate the registration</param>
        /// <returns>A response indicating success or failure of the operation</returns>
        public RegisterResponse Register(RegisterRequest request)
        {
            //ensure the user has not been registered already
            if (UserRepository.FindByEmail(request.Email) != null)
            {
                return new RegisterResponse
                       {
                           Success = false,
                           Message = "Unable to register user",
                           Errors  = new[]
                           {
                               "User is already registered"
                           }
                       }
            }
            ;


            //checks if the user is above the acceptable age
            var dob = request.DateOfBirth ?? DateTime.Now; //this is because dob could be null

            if (dob.Date > DateTime.Now)
            {
                return new RegisterResponse
                       {
                           Success = false,
                           Message = "You must enter a date before today's date",
                           Errors  = new[]
                           {
                               "User does not meet the age requirement"
                           }
                       }
            }
            ;


            var minAge = DateTime.Now.AddYears(-Constants.UserMinimumAge); //minage is todays date minus 18 years

            if (dob.Date > minAge.Date)
            {
                return new RegisterResponse
                       {
                           Success = false,
                           Message = "Unable to register user. You must be at least " + Constants.UserMinimumAge +
                                     " to register",
                           Errors = new[]
                           {
                               "User does not meet the age requirement"
                           }
                       }
            }
            ;

            //validaite that the input phone number is within 10 digits
            string phoneNo = request.PhoneNumber.Replace(" ", "");

            if (phoneNo.Length > 10)
            {
                return new RegisterResponse
                       {
                           Success = false,
                           Message = "Phone number must be 10 digits long",
                           Errors  = new[]
                           {
                               "User's phone number is not valid"
                           }
                       }
            }
            ;

            //generate a one time password
            var otpgenerator = new Random();
            var otpRecord    = otpgenerator.Next(100000, 999999).ToString();

            //register the user first
            var user = new User
            {
                FirstName = request.FirstName,
                LastName  = request.LastName,
                Email     = request.Email,
                Password  = Encryption.EncryptString(request.Password),
                OTP       = otpRecord,
                UserGroup = Constants.UserGroupName,
                Status    = Constants.UserOTPStatus
            };


            //Mail.SMTPMailer(request.Email, request.FirstName, otpRecord);
            UserRepository.Add(user);

            //populate the registration table now using the account ID of the registered user
            var registration = new Registration
            {
                AccountID           = user.AccountID,
                AddressLine1        = request.AddressLine1,
                AddressLine2        = request.AddressLine2,
                DateOfBirth         = request.DateOfBirth.Value,
                DriversLicenceID    = request.LicenceNumber,
                DriversLicenceState = request.LicenceState,
                PhoneNumber         = phoneNo,
                Postcode            = request.Postcode,
                State  = request.State,
                Suburb = request.Suburb
            };

            RegistrationRepository.Add(registration);

            var emailTemplate = TemplateRepository.FindAll().FirstOrDefault();

            if (emailTemplate == null)
            {
                return(new RegisterResponse
                {
                    Success = false,
                    Message = "An error has occurred",
                    Errors = new[]
                    {
                        "User account registered but no email sent. No email template defined."
                    }
                });
            }

            //convert the email template to replace the keys within the template
            string subject = EmailKeyReplacer(emailTemplate.Subject, user);
            string title   = EmailKeyReplacer(emailTemplate.Title, user);
            string body    = EmailKeyReplacer(emailTemplate.Body, user);
            string footer  = EmailKeyReplacer(emailTemplate.Footer, user);

            //This will send an email based on the fields passed
            EmailProvider.Send(request.Email, subject, title, body, footer);

            //return successful operation
            return(new RegisterResponse
            {
                Success = true,
                Message =
                    $"User {user.Email} has been created. An email to validate this email address will be sent shortly."
            });
        }