Exemplo n.º 1
0
        public static void ResendTaskEmail(string TaskIDs, int siteId, int programId, int userId)
        {
            List <UserTaskEmail> lstTasks;

            try
            {
                var siteEmailSetting = GetSiteEmailNotificationSettings(siteId);

                if (siteEmailSetting.SendEmailOnTaskCreation == true)
                {
                    lstTasks = GetTaskDetailsForSendingEmail(TaskIDs, siteId, programId, userId);
                    EmailHelpers.SendTaskEmailAfterSave(lstTasks, null, siteId, userId, null, ResendEmail: true);
                }
            }
            catch (Exception ex)
            {
                string sqlParam   = "";
                string methodName = "ResendTaskEmail";
                new ExceptionLogServices().ExceptionLogInsert(ex.Message.ToString(), "", methodName, userId, null, sqlParam, string.Empty);
            }
            finally
            {
                lstTasks = null;
            }
        }
Exemplo n.º 2
0
        private async void EmailReceipt(WorkOrderPaymentDTO workOrderPayment)
        {
            try
            {
                if (Customer.Person.person_id > 0)
                {
                    EmailHelpers emailHelper = new EmailHelpers();

                    EOMailMessage mailMessage = new EOMailMessage();

                    string emailHtml = String.Empty;

                    if (!String.IsNullOrEmpty(Customer.Person.email))
                    {
                        GenericGetRequest         request         = new GenericGetRequest("GetWorkOrderPrices", "workOrderId", workOrderPayment.WorkOrderId);
                        GetWorkOrderPriceResponse workOrderPrices = await((App)App.Current).GetRequest <GetWorkOrderPriceResponse>(request);

                        emailHtml = emailHelper.ComposeReceipt(currentWorkOrder, workOrderPayment, workOrderPrices);

                        mailMessage = new EOMailMessage("*****@*****.**", Customer.Person.email, "Elegant Orchids Receipt", emailHtml, "Orchids@5185");
                    }
                    else //let EO know the customer needs to add an email address
                    {
                        emailHtml = emailHelper.ComposeMissingEmail(Customer);

                        mailMessage = new EOMailMessage("*****@*****.**", "*****@*****.**", "Missing Customer Email", emailHtml, "Orchids@5185");
                    }

                    Email.SendEmail(mailMessage);
                }
            }
            catch (Exception ex)
            {
            }
        }
Exemplo n.º 3
0
        public static void SendTaskEmailAfterSave(string TaskIDs, int siteId, int programId, int userId, List <UserTaskEmail> lstTaskPreviousData, string observationTitle = "")
        {
            List <UserTaskEmail> lstTasks;

            try
            {
                var siteEmailSetting = GetSiteEmailNotificationSettings(siteId);

                if (siteEmailSetting.SendEmailOnTaskCreation == true)
                {
                    lstTasks = GetTaskDetailsForSendingEmail(TaskIDs, siteId, programId, userId);

                    var ccUserIds = String.Join(";", lstTasks.Select(a => a.CCUserIDs).Distinct());
                    var ccUsers   = GetUsers(ccUserIds, siteId);

                    EmailHelpers.SendTaskEmailAfterSave(lstTasks, lstTaskPreviousData, siteId, userId, ccUsers, observationTitle);
                }
            }
            catch (Exception ex)
            {
                string sqlParam   = "";
                string methodName = "SendTaskEmail";
                new ExceptionLogServices().ExceptionLogInsert(ex.Message.ToString(), "", methodName, userId, siteId, sqlParam, string.Empty);
            }
            finally
            {
                lstTasks            = null;
                lstTaskPreviousData = null;
            }
        }
Exemplo n.º 4
0
 public void TestInvalidAddresses()
 {
     for (int i = 0; i < InvalidAddresses.Length; i++)
     {
         Assert.IsFalse(EmailHelpers.Validate(InvalidAddresses[i]), "Invalid Address #{0}", i);
     }
 }
        public async Task SendEmailAsync(string[] recipients, string templateId, Dictionary <string, object> personalisation, string groupReference)
        {
            if (groupReference == null)
            {
                groupReference = Guid.NewGuid().ToString();
            }

            var now = DateTime.UtcNow;

            foreach (var recipient in recipients)
            {
                _logger.LogTrace($"Email: E:{EmailHelpers.AnonymiseEmailAddress(recipient)}, T:{templateId}, G:{groupReference}");

                var response = _notifyService.SendEmail(recipient, templateId, personalisation, groupReference);

                _logger.LogInformation($"Email response id: {response.id}");
                var notification = new SchoolExperienceData.Entities.Notification
                {
                    EmailAddress       = recipient,
                    NotificationId     = response.id,
                    SendGroupReference = groupReference,
                    Sent       = now,
                    TemplateId = templateId,
                };

                _dbContext.Notifications.Add(notification);
            }

            await _dbContext.SaveChangesAsync().ConfigureAwait(false);
        }
 public static IEnumerable <string> List(
     [HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequest req,
     [Table("EmailList")] CloudTable cloudTable,
     ILogger log)
 {
     return(EmailHelpers.GetEmailEntities(cloudTable, "Moderator").Select(e => e.Email));
 }
Exemplo n.º 7
0
        public IActionResult DeleteCard(string cusID, string cardID)
        {
            APIResponseData responseData = new APIResponseData();

            responseData.StatusCode = 0;
            responseData.Message    = "Failed.";
            try
            {
                var trans = StripeHelpers.RemoveCard(cusID, cardID);

                var CardModel = _mapper.Map <Card, CardStripeModel>(trans);


                responseData.Message     = "Successfully.";
                responseData.StatusCode  = 1;
                responseData.Result.Data = trans;
            }
            catch (Exception ex)
            {
                responseData.Message    = "Something went wrong, please try again.";
                responseData.StatusCode = 0;

                EmailHelpers.SendEmail(new Common.DTO.ErrorInfo()
                {
                    Section   = "AQ Request DeleteCard",
                    Exception = ex
                });
            }

skipToReturn:        //label use to force return
            return(Ok(responseData));
        }
Exemplo n.º 8
0
        public async Task <ActionResult <User> > Create(UserCreate user)
        {
            string pass = user.Password;

            user.Password = AuthenticationHelpers.EncrpytPassword(user.Password);

            User created = await _userService.Create(user);

            if (!_hostEnvironment.EnvironmentName.Equals("Development", StringComparison.OrdinalIgnoreCase))
            {
                EmailHelpers.SendRegistrationConfirmationEmail(created.TechMail, created.Username, pass);
            }

            await _logService.Create(new Log(
                                         null,
                                         created.Id,
                                         DateTime.UtcNow,
                                         "Document created.",
                                         "auth.users",
                                         created.Id,
                                         JsonSerializer.Serialize(created)
                                         ));

            return(Ok(user));
        }
Exemplo n.º 9
0
        public ActionResult SearchPayment(string Today, string FromDate)
        {
            APIResponseData responseData = new APIResponseData();

            responseData.StatusCode = 0;
            responseData.Message    = "Failed.";
            try
            {
                var tday    = Convert.ToDateTime(Today);
                var fday    = Convert.ToDateTime(FromDate);
                var results = _TransactionsService.GetSearchTransaction(tday, fday).ToList();

                responseData.Message     = "Successfully.";
                responseData.StatusCode  = 1;
                responseData.Result.Data = results;
            }
            catch (Exception ex)
            {
                responseData.Message    = "Something went wrong, please try again.";
                responseData.StatusCode = 0;

                EmailHelpers.SendEmail(new Common.DTO.ErrorInfo()
                {
                    Section   = "AQ SearchPayment",
                    Exception = ex
                });
            }

skipToReturn:        //label use to force return
            return(Ok(responseData));
        }
Exemplo n.º 10
0
 public void TestValidAddresses()
 {
     for (int i = 0; i < ValidAddresses.Length; i++)
     {
         Assert.IsTrue(EmailHelpers.Validate(ValidAddresses[i]), "Valid Address #{0}", i);
     }
 }
Exemplo n.º 11
0
        public IActionResult GetTokenCard(CardModel card)
        {
            APIResponseData responseData = new APIResponseData();

            responseData.StatusCode  = 0;
            responseData.Message     = "Failed.";
            responseData.Result.Data = "";
            try
            {
                var result = StripeHelpers.GetTokenCard(card);
                if (!string.IsNullOrEmpty(result))
                {
                    responseData.Message     = "Successfully.";
                    responseData.StatusCode  = 1;
                    responseData.Result.Data = result;
                }
            }
            catch (Exception ex)
            {
                responseData.Message    = "Something went wrong, please try again.";
                responseData.StatusCode = 0;
                EmailHelpers.SendEmail(new Common.DTO.ErrorInfo()
                {
                    Section   = "AQ GetTokenCard",
                    Exception = ex
                });
            }

            return(Ok(responseData));

            //return "value";
        }
        // TODO: change timer to once per hour (0 0 * * * *)
        public static async Task Run(
            [TimerTrigger("0 */1 * * * *")] TimerInfo myTimer,
            [Queue("srkwfound")] CloudQueue cloudQueue,
            [Table("EmailList")] CloudTable cloudTable,
            [SendGrid(ApiKey = "SendGridKey")] IAsyncCollector <SendGridMessage> messageCollector,
            ILogger log)
        {
            log.LogInformation("Checking if there are items in queue");
            await cloudQueue.FetchAttributesAsync();

            if (cloudQueue.ApproximateMessageCount == 0)
            {
                log.LogInformation("No items in queue");
                return;
            }

            log.LogInformation("Creating email message");
            var body = await CreateBody(cloudQueue);

            log.LogInformation("Retrieving email list and sending notifications");
            foreach (var emailEntity in EmailHelpers.GetEmailEntities(cloudTable, "Subscriber"))
            {
                var email = EmailHelpers.CreateEmail(Environment.GetEnvironmentVariable("SenderEmail"),
                                                     emailEntity.Email, "Notification: Orca detected!", body);
                await messageCollector.AddAsync(email);
            }
        }
Exemplo n.º 13
0
        private void EmailReceipt()
        {
            try
            {
                if (buyer.Count == 1)
                {
                    if (!String.IsNullOrEmpty(buyer[0].Person.email))
                    {
                        ((App)App.Current).GetWorkOrderPayment(workOrderId).ContinueWith(a => WorkOrderPaymentLoaded(a.Result));
                    }
                    else //let EO know the customer needs to add an email address
                    {
                        EmailHelpers emailHelper = new EmailHelpers();

                        EOMailMessage mailMessage = new EOMailMessage();

                        string emailHtml = emailHelper.ComposeMissingEmail(buyer[0]);

                        mailMessage = new EOMailMessage("*****@*****.**", "*****@*****.**", "Missing Customer Email", emailHtml, "Orchids@5185");

                        Email.SendEmail(mailMessage);
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
Exemplo n.º 14
0
        public ActionResult GetToken(string user, string pass)
        {
            APIResponseData responseData = new APIResponseData();

            responseData.StatusCode  = 0;
            responseData.Message     = "Failed.";
            responseData.Result.Data = "";

            try
            {
                var token = _ILoginService.Login(user, pass);
                if (!string.IsNullOrEmpty(token))
                {
                    responseData.Message     = "Successfully.";
                    responseData.StatusCode  = 1;
                    responseData.Result.Data = token;
                }
            }
            catch (Exception ex)
            {
                responseData.Message    = "Something went wrong, please try again.";
                responseData.StatusCode = 0;

                EmailHelpers.SendEmail(new Common.DTO.ErrorInfo()
                {
                    Section   = "AQ GetToken",
                    Exception = ex
                });
            }

            return(Ok(responseData));
        }
Exemplo n.º 15
0
        public async Task <IActionResult> Update([FromHeader] string authToken, string id, UserUpdate userIn)
        {
            if (!await _authenticationService.CheckAccess(authToken, "userMgr"))
            {
                return(Unauthorized());
            }

            var user = await _userService.Get(id);

            if (user == null)
            {
                return(NotFound());
            }

            if (!user.Password.Equals(userIn.Password))
            {
                // TODO: Check to verify this works on the stockroom server
                if (!_hostEnvironment.EnvironmentName.Equals("Development", StringComparison.OrdinalIgnoreCase))
                {
                    EmailHelpers.SendPasswordResetEmail(userIn.TechMail, userIn.Password);
                }
                userIn.Password = AuthenticationHelpers.EncrpytPassword(userIn.Password);

                // Kill all active sessions
                await _tokenService.InvalidateUserTokens(user.Id);
            }

            var permDiff = user.Permissions.Except(userIn.Permissions);
            var roleDiff = user.Roles.Except(userIn.Roles);
            var certDiff = user.Certs.Except(userIn.Certs);

            if (permDiff.Count() != 0 || roleDiff.Count() != 0 || certDiff.Count() != 0)
            {
                // Kill all active sessions
                await _tokenService.InvalidateUserTokens(user.Id);
            }

            if (user.CountryCode != null)
            {
                if (!user.CountryCode.Equals(userIn.CountryCode) || !user.PhoneNumber.Equals(userIn.PhoneNumber))
                {
                    userIn.PhoneVerifiedFlag     = false;
                    userIn.PhoneVerificationCode = await SMSHelpers.SendVerificationCode(userIn.CountryCode, userIn.PhoneNumber);
                }
            }

            _userService.Update(user, userIn);

            await _logService.Create(new Log(
                                         null,
                                         AuthenticationHelpers.GetUserIdFromToken(authToken),
                                         DateTime.UtcNow,
                                         "Document modified.",
                                         "auth.users",
                                         id,
                                         JsonSerializer.Serialize(ecestockroom_api.Models.Authentication.User.FromUpdate(user, userIn))
                                         ));

            return(Ok());
        }
 public static async Task <IActionResult> Run(
     [HttpTrigger(AuthorizationLevel.Function, "post", "delete")] HttpRequest req,
     [Table("EmailList")] CloudTable cloudTable,
     ILogger log)
 {
     return(await EmailHelpers.UpdateEmailList <ModeratorEmailEntity>(req, cloudTable, log));
 }
Exemplo n.º 17
0
        void UploadUploadCommandComplete(object sender, EventArgs e)
        {
            _currentNumber++;
            if (_currentNumber < _vm.Vehicles.Count)
            {
                _vm.Vehicles[_currentNumber].Upload.Execute(null);
            }
            else
            {
                _vm.ResultMessage = "The uploading process has finished.";
                _isEnable         = false;
                _vm.IsEnableSync  = false;

                EmailHelpers.SendEmailByWcfService(_vm.Vehicles, ((App)Application.Current).Dealer);

                if (_vm.IsPortableDevice)
                {
                    PortableDeviceHelper.DeleteFromWpdToHardDrive();
                    const string backupPortablePath = @"C:\\VincaptureTemporary";

                    if (Directory.Exists(backupPortablePath))
                    {
                        FileHelper.DeleteFilesAndFoldersRecursively(backupPortablePath);
                    }
                }
                else
                {
                    if (!String.IsNullOrEmpty(_vm.DealerFolder) && Directory.Exists(_vm.DealerFolder))
                    {
                        FileHelper.DeleteFilesAndFoldersRecursively(_vm.DealerFolder);
                    }
                }
            }
        }
Exemplo n.º 18
0
        public bool SendNewPassword()
        {
            if (this.DBInstance == null)
            {
                throw new Exception("Database instance must be passed before calling SendNewPassword");
            }

            bool bSuccessfullyReset = false;

            // someone actually passed an email rather than just the page loading.
            if (!string.IsNullOrEmpty(this.Email))
            {
                // let the view know someone actually tried to reset their password.
                this.AttemptedReset = true;

                // try to find the user by email
                var userToReset = this.DBInstance.Admins.FirstOrDefault(user => user.Email.ToLower() == this.Email.ToLower());

                // reset the user
                if (userToReset != null)
                {
                    string sPasswordToSave = System.Web.Security.Membership.GeneratePassword(8, 5);
                    userToReset.ForceChangePassword = true;
                    userToReset.Password            = sPasswordToSave;

                    bSuccessfullyReset = EmailHelpers.SendEmail(
                        new System.Net.Mail.MailMessage(EmailHelpers.SEND_EMAIL_ADDRESS, userToReset.Email)
                    {
                        Subject    = "Miracles for Mito -- Password Reset",
                        Body       = @"Dear " + userToReset.FirstName + " " + userToReset.LastName + @",<br/><br/>
								Your password has been reset. Your credentials are as follows:<br/><br/>
								<strong>Username:</strong> <em>[this email]</em><br/>
								<strong>Password:</strong> "                                 + sPasswordToSave + @"<br/><br/>
						
							Sincerely,<br/>
							The Miracles for Mito Dev Team
							"                            ,
                        IsBodyHtml = true
                    }
                        );

                    // only save the changes if the email was actually sent.
                    if (bSuccessfullyReset)
                    {
                        this.DBInstance.SaveChanges();
                    }
                    else
                    {
                        this.ErrorMessage = "Unable to reset password. Please try again.";
                    }
                }
                else
                {
                    this.ErrorMessage = string.Format("Unable to locate user {0}.", this.Email);
                }
            }

            return(bSuccessfullyReset);
        }
Exemplo n.º 19
0
        public async Task <IActionResult> VolunteerJobRemoval(JobAssignmentViewModel vm)
        {
            var user = await userManager.GetUserAsync(User);

            VolunteerRepository repo = new VolunteerRepository(configModel.ConnectionString);
            VolunteerJobModel   job;

            // This endpoint should only be accessible if the user is a staff member or if the user is trying to remove a job they have signed themselves up for
            if (user.VolunteerId != vm.VolunteerId && !User.IsInRole(UserHelpers.UserRoles.Staff.ToString()))
            {
                return(Utilities.ErrorJson("Unauthorized"));
            }

            // The first check is so we can skip a call to the database if the user is signing up for a job on their own - clearly the user id is valid in that case
            if (vm.VolunteerId != user.VolunteerId && repo.GetVolunteer(vm.VolunteerId) == null)
            {
                return(Utilities.ErrorJson("Invalid volunteer id"));
            }

            if (vm.Date == DateTime.MinValue)
            {
                return(Utilities.ErrorJson("Must specify a date"));
            }

            job = repo.GetVolunteerJob(vm.JobId, vm.Date);
            if (job == null)
            {
                return(Utilities.ErrorJson("Invalid volunteer job id"));
            }

            if (!repo.CheckSignedUpForJob(vm.JobId, vm.VolunteerId, vm.Date))
            {
                return(Utilities.ErrorJson("Not currently signed up for this job"));
            }

            if (job.CurrentNumber <= job.Min)
            {
                try
                {
                    await EmailHelpers.SendEmail("*****@*****.**", $"{vm.Date.ToString("dd/MM/yyyy")} - {job.Name} may be understaffed",
                                                 $"A cancellation has left {job.Name} with fewer than its minimum of {job.Min} volunteers signed up on {vm.Date.ToString("dd/MM/yyyy")}.", configModel.EmailOptions);
                }
                catch (Exception)
                {
                    // This is in case the email fails to send - we still want to cancel the job, since the email isn't critical
                }
            }

            try
            {
                repo.RemoveVolunteerJobAssignment(vm.VolunteerId, vm.JobId, vm.Date);
            }
            catch (Exception e)
            {
                return(Utilities.ErrorJson(e.Message));
            }

            return(Utilities.NoErrorJson());
        }
Exemplo n.º 20
0
        public async Task InitializeAsync()
        {
            await DatabaseHelpers.ResetDatabase();

            await EmailHelpers.ResetEmail();

            await StorageHelpers.ResetStorage();

            await SetupConfiguration();
        }
        public void Test1(string emailAddress, string expectedResult)
        {
            // Arrange

            // Act
            var result = EmailHelpers.AnonymiseEmailAddress(emailAddress);

            // Assert
            result.Should().Be(expectedResult);
        }
Exemplo n.º 22
0
        private void WorkOrderPricesLoaded(WorkOrderResponse workOrder, WorkOrderPaymentDTO payment, GetWorkOrderPriceResponse workOrderPriceResponse)
        {
            EmailHelpers emailHelper = new EmailHelpers();

            EOMailMessage mailMessage = new EOMailMessage();

            string emailHtml = emailHelper.ComposeReceipt(workOrder, payment, workOrderPriceResponse);

            mailMessage = new EOMailMessage("*****@*****.**", buyer[0].Person.email, "Elegant Orchids Receipt", emailHtml, "Orchids@5185");

            Email.SendEmail(mailMessage);
        }
Exemplo n.º 23
0
        public async Task <IActionResult> PasswordResetRequest(PasswordResetViewModel vm)
        {
            string email = vm.Email;
            string token;
            var    user = await userManager.FindByNameAsync(email);

            VolunteerRepository repo = new VolunteerRepository(configModel.ConnectionString);
            VolunteerModel      profile;

            if (!UserHelpers.IsValidEmail(email))
            {
                return(Utilities.ErrorJson("Must provide a valid email address"));
            }

            if (user == null)
            {
                return(Utilities.NoErrorJson());
            }

            try
            {
                profile = repo.GetVolunteer(user.VolunteerId);
            }
            catch (Exception)
            {
                return(Utilities.ErrorJson("Unable to get volunteer profile - please try again later."));
            }

            if (profile == null)
            {
                return(Utilities.ErrorJson("Unable to get volunteer profile - please try again later."));
            }

            token = await userManager.GeneratePasswordResetTokenAsync(user);

            try
            {
                await EmailHelpers.SendEmail(email, "Password Reset - OCC",
                                             $"Hello {profile.PreferredName + " " + profile.LastName},\n\n" +
                                             "You are receiving this email because you requested a password reset for Orlando Children's Church. " +
                                             "In order to reset your password, please follow the link below, or copy/paste the code below when prompted.\n\n" +
                                             "Link: https://www.operation-portal.com/password-reset-confirm?email=" + HttpUtility.UrlEncode(email) + "&token=" + HttpUtility.UrlEncode(token) + "\n\n" +
                                             $"Code: {token}\n\n" +
                                             "This code will be valid for 1 hour.  If you did not request a password reset, please ignore this email.",
                                             configModel.EmailOptions);
            }
            catch (Exception)
            {
                return(Utilities.ErrorJson("An error occurred and a password reset email could not be sent.  Please try again later."));
            }

            return(new JsonResult(new { token = token }));
        }
Exemplo n.º 24
0
        public void Do(string login, string password, string email, string emailPassword, string additionalInfo, string userEmail)
        {
            //Url.Action("BuyDetails", "Order", new { id = offer.Order.Id }, protocol: Request.Url.Scheme)).ToString()
            string body = EmailHelpers.AccountData(login, password, email, emailPassword, additionalInfo).ToString();

            identityMessageService.SendAsync(new IdentityMessage()
            {
                Body    = body,
                Subject = "Данные от аккаунта",

                Destination = userEmail
            }).Wait();
        }
Exemplo n.º 25
0
        public void Do(int orderId, string userEmail, string currentStatus, string callbackUrl)
        {
            //Url.Action("BuyDetails", "Order", new { id = offer.Order.Id }, protocol: Request.Url.Scheme)).ToString()
            string body = EmailHelpers.ActivateForm($"Статус вашего заказа (id:{orderId}) изменился на: {currentStatus}", "Посмотреть детали", callbackUrl).ToString();

            identityMessageService.SendAsync(new IdentityMessage()
            {
                Body    = body,
                Subject = "Статус заказа изменился",

                Destination = userEmail
            }).Wait();
        }
Exemplo n.º 26
0
        public void TracerMobileCustomerSupportEmail(CustomerSupport customerSupport)
        {
            //Insert record to database
            int rowCount = InsertCustomerSupport(customerSupport);


            //Load Email Template
            string TMobileCustomerSupportEmailTo   = ConfigurationManager.AppSettings["TracerMobileCustomerSupportEmailTo"].ToString();
            string TMobileCustomerSupportEmailFrom = ConfigurationManager.AppSettings["TracerMobileCustomerSupportEmailFrom"].ToString();
            string smtpServer = ConfigurationManager.AppSettings["TracerSMTPserver"];
            string subject    = "Customer Support Request From Tracers Mobile App";
            var    nvc        = new NameValueCollection(6);

            nvc["USEREMAIL"]    = customerSupport.Email;
            nvc["USERFULLNAME"] = customerSupport.UserName;
            nvc["USERID"]       = customerSupport.UserID;
            nvc["SITEID"]       = customerSupport.SiteID;
            nvc["HCOID"]        = (customerSupport.HCOID == 0) ? "n/a" : customerSupport.HCOID.ToString();
            nvc["SUBMITTIME"]   = DateTime.Now.ToString(); //customerSupport.SubmitTime;
            nvc["SUBJECT"]      = customerSupport.Subject;
            nvc["PROGRAM"]      = customerSupport.ProgramName;
            nvc["BODY"]         = customerSupport.Body;

            //Create body from template
            string body = EmailServices.LoadEmailTemplate("Support.htm", nvc);

            //Send Email
            //(string to, string cc, string bcc, string replyTo,
            //string subject, string body, string attachment, bool isError, string sMTPServer,
            //string emailUserName, string emailPassword, string emailErrorTo,
            //string emailTestsTo, string emailFrom, int userId, int siteId)

            EmailHelpers.SendSMTPEmail(
                TMobileCustomerSupportEmailTo,
                string.Empty,
                string.Empty,
                customerSupport.Email,
                subject,
                body,
                string.Empty,
                false,
                smtpServer,
                string.Empty,
                string.Empty,
                string.Empty,
                string.Empty,
                TMobileCustomerSupportEmailFrom,
                Convert.ToInt32(customerSupport.UserID),
                Convert.ToInt32(customerSupport.SiteID)
                );
        }
        public static async Task Run(
            [CosmosDBTrigger(
                 databaseName: "predictions",
                 collectionName: "metadata",
                 ConnectionStringSetting = "aifororcasmetadatastore_DOCUMENTDB",
                 LeaseCollectionName = "leases",
                 LeaseCollectionPrefix = "moderator",
                 CreateLeaseCollectionIfNotExists = true)] IReadOnlyList <Document> input,
            [Table("EmailList")] CloudTable cloudTable,
            [SendGrid(ApiKey = "SendGridKey")] IAsyncCollector <SendGridMessage> messageCollector,
            ILogger log)
        {
            if (input == null || input.Count == 0)
            {
                log.LogInformation("No updated records");
                return;
            }

            var      newDocumentCreated = false;
            DateTime?documentTimeStamp  = null;

            foreach (var document in input)
            {
                if (!document.GetPropertyValue <bool>("reviewed"))
                {
                    newDocumentCreated = true;
                    documentTimeStamp  = document.GetPropertyValue <DateTime>("timestamp");
                    break;
                }
            }

            if (!newDocumentCreated)
            {
                log.LogInformation("No unreviewed records");
                return;
            }

            // TODO: make better email
            string body = EmailTemplate.GetModeratorEmailBody(documentTimeStamp);

            log.LogInformation("Retrieving email list and sending notifications");
            foreach (var emailEntity in EmailHelpers.GetEmailEntities(cloudTable, "Moderator"))
            {
                var email = EmailHelpers.CreateEmail(Environment.GetEnvironmentVariable("SenderEmail"),
                                                     emailEntity.Email, "New Orca Call Identified", body);
                await messageCollector.AddAsync(email);
            }
        }
Exemplo n.º 28
0
        public bool SendEmailAttachemnt(Email email, int actionTypeId, byte[] fileContent, int userId, int siteId, string siteName, string fullName, string reportName)
        {
            bool returnStatus = true;

            try
            {
                // var reportName =  "Tracer By CMS Tag Report";

                string dtNow = DateTime.Now.ToString("MM-dd-yyyy_hhmmssfff_tt");

                Random rn      = new Random(siteId + userId);
                var    seedVal = rn.Next(99999999);

                // Generate a unique file name.
                string filename = string.Format("{0}_{1}{2}.pdf", reportName, dtNow.ToString(), seedVal.ToString());

                // Create email body from email template file
                var nvc = new NameValueCollection(3);
                nvc["TONAME"]   = fullName;
                nvc["MESSAGE"]  = "Please find the report for observation <b>" + email.Title + "</b> attached.";
                nvc["COMMENTS"] = !string.IsNullOrEmpty(email.Comments) ? "Comments:" + email.Comments : "";

                // Create body from template
                email.Body = LoadEmailTemplate("EmailReport.htm", nvc);

                string fileGuid = FilesServices.SaveAttachmentFile(filename, fileContent, Enums.ApplicationCode.Tracers.ToString()); //,
                email.Guid = fileGuid;

                //string path = email.AttachmentLocation[0];
                //if (path != null)
                //{
                //    int pos = path.LastIndexOf("\\") + 1;
                //    string fileName = path.Substring(pos, path.Length - pos);
                //    string fileGuid = FilesServices.SaveAttachmentFile(fileName, fileContent, Enums.ApplicationCode.Tracers.ToString()); //,
                //    email.Guid = fileGuid;
                //}


                EmailHelpers.SendEmail(email, actionTypeId, siteId, userId, siteName, fullName);
            }
            catch (Exception ex)
            {
                string error = ex.Message.ToString();
                returnStatus = false;
            }

            return(returnStatus);
        }
Exemplo n.º 29
0
        private void SendPostedEmail(string email, BlogPost post)
        {
            EmailHelpers.SendEmail(
                new System.Net.Mail.MailMessage(EmailHelpers.SEND_EMAIL_ADDRESS, email)
            {
                Subject = "Miracles for Mito New Blog Post!",
                Body    = "The Miracles for Mito Blog team has posted a new blog post, <a title=\"Click here to visit the Miracles for Mito Blog\" href=\"" +
                          (string.Format("~/Blog/Post/{0}", post.SEOLink)).ToAbsoluteUrl() +
                          "\">" + post.Title + "</a>.<br/><br/>" +
                          @"Sincerely,<br/>
					The Miracles for Mito Dev Team<br/><br/>"                     +
                          "<a href=\"" + (string.Format("~/Unsubscribe/{0}", SimpleCrypto.Encrypt(email))).ToAbsoluteUrl() + "\">Click here to unsubscribe from these emails</a>",
                IsBodyHtml = true
            }
                );
        }
Exemplo n.º 30
0
        // POST api/AdminUser (Create in CRUD)
        public HttpResponseMessage PostAdminUser(AdminUser user)
        {
            if (ModelState.IsValid)
            {
                // email must be unique
                if (db.Admins.Where(adminUser => adminUser.Email.ToLower() == user.Email.ToLower()).Count() > 0)
                {
                    ModelState.AddModelError("EmailNotUnique", "A user with this email address already exists.");
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                }

                string sPasswordToSave = System.Web.Security.Membership.GeneratePassword(8, 5);
                // create a random password
                user.Password = sPasswordToSave;
                // force them to change their password next time they login
                user.ForceChangePassword = true;

                db.Admins.Add(user);
                db.SaveChanges();

                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, user);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = user.ID }));

                EmailHelpers.SendEmail(
                    new System.Net.Mail.MailMessage(EmailHelpers.SEND_EMAIL_ADDRESS, user.Email)
                {
                    Subject    = "Miracles for Mito -- User Account",
                    Body       = @"Dear " + user.FirstName + " " + user.LastName + @",<br/><br/>
							You have been added as a Miracles for Mito Admin user. Your credentials are as follows:<br/><br/>
							<strong>Username:</strong> <em>[this email]</em><br/>
							<strong>Password:</strong> "                             + sPasswordToSave + @"<br/><br/>
						
						Sincerely,<br/>
						The Miracles for Mito Dev Team
						"                        ,
                    IsBodyHtml = true
                }
                    );

                return(response);
            }
            else
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }
        }