Exemplo n.º 1
0
        public void ExecuteTask_PayloadVerified_CallsSendEmailAsync()
        {
            // Arrange
            EmailNotification notification    = new EmailNotification("*****@*****.**", "plain text content");
            string            payload         = Newtonsoft.Json.JsonConvert.SerializeObject(notification);
            string            emailFromString = "*****@*****.**";
            EmailAddress      emailFrom       = new EmailAddress(emailFromString);
            EmailAddress      emailTo         = new EmailAddress(notification.RecipientEmail);
            string            subject         = "You have a new notification on DeX";
            SendGridMessage   msg             = MailHelper.CreateSingleEmail(emailFrom, emailTo,
                                                                             subject, notification.TextContent, notification.HtmlContent);
            Mock <ISendGridClient> sendgridMock = new Mock <ISendGridClient>();

            sendgridMock.Setup(x => x.SendEmailAsync(It.Is <SendGridMessage>(x => x.From == emailFrom &&
                                                                             x.Personalizations.First().Tos.First() == emailTo),
                                                     It.IsAny <CancellationToken>())).Verifiable();

            EmailSender emailSender = new EmailSender(sendgridMock.Object, emailFromString);

            // Act
            emailSender.ParsePayload(payload);
            emailSender.ExecuteTask();

            // Assert
            sendgridMock.Verify();
        }
Exemplo n.º 2
0
        // AJAX
        // Reject Department Requests
        public ActionResult Ajax_Reject_Department_Request(ajax_model ajax_model_data)
        {
            ajax_model ajax_data = new ajax_model
            {
                name      = ajax_model_data.name,
                main_data = ajax_model_data.main_data,
            };

            using (var db = new DataBaseContext())
            {
                List <orders> order_lis = db.orders_repository.Where(or => or.staff_obj.department_obj.department_name == ajax_data.name).ToList();

                foreach (orders or in order_lis)
                {
                    or.order_status = "Rejected_by_Clerk";

                    db.SaveChanges();
                }
            }
            object reply_to_client = new
            {
                key_itemname_lis = "SUCCESS",
            };

            //Email Notification
            staff  rep      = StaffData.GetStaffByName(DepartmentData.GetRepresentativebyDepName(ajax_data.name));
            string emailadd = rep.email;
            Task   task     = Task.Run(() => {
                EmailNotification.SendNotificationEmailToEmployee(emailadd, "New Disbursment Order Reminder", "There is a new disbursment order to your department was rejected by store clerk.");
            });

            return(Json(reply_to_client, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 3
0
        public IActionResult Contact(ContactView model)
        {
            CaptchaResponse response = ValidateCaptcha(Request.Form["g-recaptcha-response"]);

            if (response.Success && ModelState.IsValid)
            {
                try
                {
                    EmailNotification email = new EmailNotification();
                    email.Name    = model.Name;
                    email.Subject = "Message from Resgrid Contact Form";
                    email.From    = model.Email;
                    email.Body    = model.Message;

                    _emailService.Notify(email);

                    model.Result  = "Your message has been sent. We will get back to you within 48 hours M-F.";
                    model.Name    = String.Empty;
                    model.Email   = String.Empty;
                    model.Message = String.Empty;
                }
                catch (Exception ex)
                {
                }


                return(View(model));
            }

            return(View(model));
        }
        /// <summary>
        /// Send notification mail with the results of price push to Streamline.
        /// </summary>
        /// <param name="logWrittenDateTime">Log written date and time.</param>
        public void SendNotificationToStreamLine(DateTime logWrittenDateTime)
        {
            var config = new TemplateServiceConfiguration
            {
                BaseTemplateType       = typeof(HtmlSupportTemplateBase <>),
                DisableTempFileLocking = true,
                CachingProvider        = new DefaultCachingProvider(t => { })
            };

            var pricingPushLogger = new OperationsJsonLogger <PricePushResult>(Config.I.PricingPushAttemptsLogFile);
            var pricingPushlogs   = pricingPushLogger.GetLogRecordsForExactDateTime(logWrittenDateTime);
            var streamLineLogs    = pricingPushlogs.Where(p => p.Channel == Channel.StreamLine || p.Channel == Channel.Common);
            var templatePath      = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var template          = File.ReadAllText(Path.Combine(templatePath, "Templates/StreamLinePricingPushNotificationTemplate.cshtml"));

            using (var service = RazorEngineService.Create(config))
            {
                var body = service.RunCompile(template, "StreamLinePricingPushNotificationTemplate", null, new
                {
                    ProcessStartedAt    = logWrittenDateTime.ToString("yyyy-M-d HH:mm tt"),
                    ErrorsCount         = streamLineLogs.Where(p => p.LogType == PricingPushLogType.Error).Count(),
                    ParsingCSV          = streamLineLogs.Where(p => ((p.LogArea == PricePushLogArea.ParsingCSV || p.LogArea == PricePushLogArea.CSVFileNotFound) && p.LogType == PricingPushLogType.Error)),
                    PropertyDetails     = streamLineLogs.Where(p => p.LogArea == PricePushLogArea.ParsingCSV && p.LogType == PricingPushLogType.Information),
                    LoginDetails        = streamLineLogs.Where(p => p.LogArea == PricePushLogArea.Login && p.LogType == PricingPushLogType.Information),
                    LoginErrors         = streamLineLogs.Where(p => p.LogArea == PricePushLogArea.Login && p.LogType == PricingPushLogType.Error),
                    SeasonGroupErrors   = streamLineLogs.Where(p => ((p.LogArea == PricePushLogArea.SeasonGroup || p.LogArea == PricePushLogArea.ChangeSeasonGroup) && p.LogType == PricingPushLogType.Error)),
                    SeasonErrors        = streamLineLogs.Where(p => p.LogArea == PricePushLogArea.Season && p.LogType == PricingPushLogType.Error),
                    PropertyErrors      = streamLineLogs.Where(p => p.LogArea == PricePushLogArea.Property && p.LogType == PricingPushLogType.Error),
                    PriceUpdationErrors = streamLineLogs.Where(p => p.LogArea == PricePushLogArea.PriceUpdate && p.LogType == PricingPushLogType.Error),
                });

                EmailNotification.Send(Config.I.PricingPushNotificationsEmail, "Streamline Pricing Push Report", body);
            }
        }
Exemplo n.º 5
0
        public EmailNotification Send(int createdBy, EmailNotification emailNotification)
        {
            MailMessage email = new MailMessage();

            email.IsBodyHtml = emailNotification.IsBodyHtml;
            email.Body       = emailNotification.Body;
            if (!string.IsNullOrEmpty(emailNotification.Bcc))
            {
                email.Bcc.Add(emailNotification.Bcc);
            }
            if (!string.IsNullOrEmpty(emailNotification.CC))
            {
                email.CC.Add(emailNotification.CC);
            }
            email.From    = new MailAddress(emailNotification.From);
            email.Subject = emailNotification.Subject;
            email.To.Add(emailNotification.To);

            SmtpClient smtp = new SmtpClient();

            smtp.Host        = emailNotification.Host;
            smtp.Credentials = new NetworkCredential(emailNotification.Username, emailNotification.Password);
            smtp.EnableSsl   = emailNotification.EnableSsl;
            smtp.Send(email);
            Create(createdBy, emailNotification);

            return(emailNotification);
        }
Exemplo n.º 6
0
        public IHttpActionResult ResignOffer(ReserveOfferDto dto)
        {
            using (var context = _provider.GetNewContext())
            {
                using (var transaction = new TransactionScope())
                {
                    Offer offer    = context.Offers.FirstOrDefault(o => o.Id == dto.OfferId);
                    User  customer = context.Users.FirstOrDefault(u => u.Username.Equals(dto.Username));
                    User  vendor   = context.Users.FirstOrDefault(x => x.Id == offer.VendorId);

                    if (offer == null || customer == null)
                    {
                        return(NotFound());
                    }
                    if (!offer.IsBooked)
                    {
                        return(BadRequest());
                    }


                    OfferInfo offerInfo    = context.OfferInfo.FirstOrDefault(o => o.Id == offer.OfferInfoId);
                    UserData  customerData = context.UserData.FirstOrDefault(x => x.Id == customer.UserDataId);
                    UserData  vendorData   = context.UserData.FirstOrDefault(x => x.Id == vendor.UserDataId);
                    Room      room         = context.Rooms.FirstOrDefault(x => x.Id == offer.RoomId);
                    Place     place        = context.Places.FirstOrDefault(x => x.Id == room.PlaceId);
                    offer.IsBooked = false;
                    offer.Customer = null;
                    context.SaveChanges();
                    //Wysłanie powiadomienia mailowego, ostatni parametr oznacza rezygnację
                    EmailNotification.SendNotification(offerInfo, place, vendorData, customerData, room, false);
                    transaction.Complete();
                }
            }
            return(Ok(true));
        }
        /// <summary>
        /// Execute the cmdlet
        /// </summary>
        public override void ExecuteCmdlet()
        {
            this.WriteIdentifiedWarning(
                cmdletName: "New-AzureRmAutoscaleNotification",
                topic: "Parameter name change",
                message: "The parameter plural names for the parameters will be deprecated in a future breaking change release in favor of the singular versions of the same names.");
            if (!(this.SendEmailToSubscriptionAdministrator || this.SendEmailToSubscriptionCoAdministrator) &&
                ((this.Webhook == null || this.Webhook.Length < 1) && (this.CustomEmail == null || this.CustomEmail.Length < 1)))
            {
                throw new ArgumentException("At least one Webhook or one CustomeEmail must be present, or the notification must be sent to the admin or co-admin");
            }

            var emailNotification = new EmailNotification
            {
                CustomEmails = this.CustomEmail,
                SendToSubscriptionAdministrator    = this.SendEmailToSubscriptionAdministrator,
                SendToSubscriptionCoAdministrators = this.SendEmailToSubscriptionCoAdministrator,
            };

            var notification = new AutoscaleNotification
            {
                Email    = emailNotification,
                Webhooks = this.Webhook
            };

            WriteObject(notification);
        }
        /// <summary>
        ///  Create EmailNotification
        /// </summary>
        public async Task CreateNotificationAsync(string[] emailsTo, string subject, string body, string creatorEmail, DateTime?sendDate, int?requestId, int?alertTypeId)
        {
            var eamilsToStr = string.Join(",", emailsTo);

            var newNotification = new EmailNotification
            {
                Id           = 0,
                Body         = body,
                Subject      = subject,
                EmailsTo     = eamilsToStr,
                IsProcessing = false,
                IsSent       = false,
                SendDate     = sendDate,

                CreatedBy = creatorEmail,
                Created   = DateTime.UtcNow,

                AlertTypeId = alertTypeId,
                RequestId   = requestId
            };

            await _contextDb.EmailNotifications.AddAsync(newNotification);

            await _contextDb.SaveChangesAsync();
        }
Exemplo n.º 9
0
        public string TransitionRequest(string id, string statusId, string notifyCustomer, string notifyManager)
        {
            int  Id = 0;
            bool notifycustomer, notifymanager = false;

            notifycustomer = notifyCustomer.ToLower().Contains("t") || notifyCustomer.ToLower().Contains("1");
            notifymanager  = notifyManager.ToLower().Contains("f") || notifyManager.ToLower().Contains("1");
            int.TryParse(id, out Id);
            Request request = dao.GetRequests(Id).First();

            request.Modified   = DateTime.Now;
            request.ModifiedBy = 2;//hard coded by as machine
            request.StatusId   = int.Parse(statusId);
            dao.SaveRequest(request);
            if (notifycustomer)
            {
                EmailNotification notification = new EmailNotification()
                {
                    RequestId = request.Id.Value, StatusId = request.StatusId.Value, To = request.Email, Subject = "Request " + id.ToString() + " Updated", Body = "body"
                };
                dao.SaveEmailNotification(notification);
            }

            if (notifymanager)
            {
                EmailNotification notification = new EmailNotification()
                {
                    RequestId = request.Id.Value, StatusId = request.StatusId.Value, To = "*****@*****.**", Subject = "Request " + id.ToString() + " Updated", Body = "body"
                };
                dao.SaveEmailNotification(notification);
            }
            return("Done!");
        }
Exemplo n.º 10
0
        //[ValidateAntiForgeryToken]
        public ActionResult UpdateUser(string id, MyProfileInfo objProfile)
        {
            ApplicationUser usr = db.Users.Find(id);

            objProfile.UserName = usr.UserName;
            if (ModelState.IsValid)
            {
                usr.Name            = objProfile.Name;
                usr.Email           = objProfile.Email;
                usr.FlatNo          = objProfile.FlatNo;
                db.Entry(usr).State = EntityState.Modified;
                db.SaveChanges();


                var formCollection = new FormCollection(HttpContext.Request.Form);
                if (formCollection["ResetPass"].ToString().ToLower() != "false")
                {
                    var token  = UserManager.GenerateEmailConfirmationToken(id);
                    var result = UserManager.ResetPassword(id, token, "abcd@1234");
                    if (result.Succeeded)
                    {
                        if (!string.IsNullOrEmpty(usr.Email))
                        {
                            EmailNotification ygcemail = new EmailNotification();
                            ygcemail.SendForgetPasswordEmail(usr, "abcd@1234");
                            ygcemail = null;
                        }
                    }
                }
                return(RedirectToAction("Users"));
            }
            return(View(objProfile));
        }
Exemplo n.º 11
0
        public bool SaveEmailNotification(EmailNotification notification)
        {
            bool result = true;

            try
            {
                OracleDao     dao     = new OracleDao(Configs.ConnectionString);
                OracleCommand command = dao.GetSprocCommand("idemia.SP_INSERTEMAIL");
                command.Parameters.Add(dao.CreateParameter("PREQUESTID", notification.RequestId));
                command.Parameters.Add(dao.CreateParameter("PSTATUSID", notification.StatusId));
                command.Parameters.Add(dao.CreateParameter("PSUBJECT", notification.Subject));
                command.Parameters.Add(dao.CreateParameter("PBODY", notification.Body));
                command.Parameters.Add(dao.CreateParameter("PTO", notification.To));
                if (command.Connection.State == System.Data.ConnectionState.Closed)
                {
                    command.Connection.Open();
                }
                command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                result = false;
            }

            return(result);
        }
Exemplo n.º 12
0
        public void SaveEmailNoticeTest()
        {
            //Arrange
            var testMail = new EmailNotice2()
            {
                UserID          = "mif",
                SchoolYear      = schoolyear,
                SchoolCode      = "0204",
                PositionType    = "LTO",
                PositionID      = "20112",
                PositionTitle   = "Posting Title English Gr.6",
                PostingNum      = "2018-20122",
                NoticePrincipal = "School Principal Name",
                EmailType       = "Repost",
                EmailTo         = "*****@*****.**",
                EmailCC         = "*****@*****.**",
                EmailFrom       = "*****@*****.**",
                EmailSubject    = "Posting Reposting Notification",
                EmailBody       = "",
                EmailFormat     = "HTML",
                Attachment1     = "",
                Attachment2     = "",
                Attachment3     = "",
            };


            string expect = "Successfully";

            //Act
            var result = EmailNotification.SaveEmailNotice(testMail);


            //Assert
            Assert.AreEqual(expect, result, $"  RePosting email notification { result}");
        }
Exemplo n.º 13
0
        public void Test_MembershipORUpgradeWithEmailNotificationUpgradeMembership()
        {
            EmailNotification emailNotification = new EmailNotification(new UpgradeMembership());
            bool res = emailNotification.DoEmailNotify();

            Assert.AreEqual(res, true);
        }
Exemplo n.º 14
0
        //public string TestEmailSettings(DepartmentCallEmail emailSettings)
        //{
        //	return _callEmailProvider.TestEmailSettings(emailSettings);
        //}

        public async Task <bool> SendReportDeliveryEmail(EmailNotification email)
        {
            using (var mail = new MailMessage())
            {
                mail.To.Add(email.To);
                mail.Subject = email.Subject;
                mail.From    = new MailAddress("*****@*****.**", "Resgrid Report Delivery");

                mail.Body       = string.Format("Your scheduled Resgrid report is attached.");
                mail.IsBodyHtml = false;

                var ms = new MemoryStream(email.AttachmentData);
                var a  = new System.Net.Mail.Attachment(ms, email.AttachmentName);
                mail.Attachments.Add(a);

                //_smtpClient.Send(mail);

                try
                {
                    await _emailSender.SendEmail(mail);

                    return(true);
                }
                catch (SmtpException sex) { }
            }

            return(false);
        }
Exemplo n.º 15
0
        public ActionResult Ajax_Reject_Request_Item(ajax_model ajax_data)
        {
            ajax_model data = new ajax_model
            {
                name      = ajax_data.name,
                main_data = ajax_data.main_data,
            };

            using (var db = new DataBaseContext())
            {
                int temp_id = Int32.Parse(data.main_data[0]);

                orders temp_order = db.orders_repository.Where(o => o.ordersId == temp_id).FirstOrDefault();
                temp_order.order_status = "Reject_by_Head";

                db.SaveChanges();
            }
            object reply_to_client = new
            {
                key_itemname_lis = "SUCCESS",
            };


            //Email Notification
            orders ord      = OrdersData.GetOrderById(Int32.Parse(data.main_data[0]));
            string emailadd = StaffData.GetStaffByName(ord.staff_obj.name).email;
            Task   task     = Task.Run(() => {
                EmailNotification.SendNotificationEmailToEmployee(emailadd, "Requisition Progress Updated", "Your requisition was just rejected by manager, please check.");
            });

            return(Json(reply_to_client, JsonRequestBehavior.AllowGet));
        }
        /// <summary>
        ///  Send notification email when the process starts
        /// </summary>
        /// <param name="processStartedDateTime">Process started time</param>
        public void SendInitialNotification(DateTime processStartedDateTime)
        {
            var config = new TemplateServiceConfiguration
            {
                BaseTemplateType       = typeof(HtmlSupportTemplateBase <>),
                DisableTempFileLocking = true,
                CachingProvider        = new DefaultCachingProvider(t => { })
            };

            bool pushPriceToAirBnb     = Config.I.PushPriceToAirBnb;
            bool pushPriceToStreamLine = Config.I.PushPriceToStreamLine;

            var templatePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var template     = File.ReadAllText(Path.Combine(templatePath, "Templates/PricingPushInitialNotificationTemplate.cshtml"));

            using (var service = RazorEngineService.Create(config))
            {
                var body = service.RunCompile(template, "PricingPushInitialNotificationTemplate", null, new
                {
                    ProcessStartedAt = processStartedDateTime.ToString("yyyy-M-d HH:mm tt"),
                    PushToAirbnb     = pushPriceToAirBnb,
                    PushToStreamline = pushPriceToStreamLine
                });

                EmailNotification.Send(Config.I.NotificationsEmail, "Pricing Push Initialized", body);
            }
        }
Exemplo n.º 17
0
        public async Task AddEmailNotificationAsync(EmailNotification emailNotification)
        {
            emailNotification.CreatedOn = DateTime.Now;

            _db.EmailNotifications.Add(emailNotification);
            await _db.SaveChangesAsync();
        }
Exemplo n.º 18
0
        public JsonResult UpdateCheckDates(string _data)
        {
            EmailNotificationExtended[] EmailNotifications = JsonConvert.DeserializeObject <EmailNotificationExtended[]>(_data, CommonFunctions.JsonDeserializerSettings);

            DateTime _d     = DateTime.Now;
            string   conStr = Session["conStr"].ToString(); //ConfigurationManager.ConnectionStrings["MySQLConnectionString"].ConnectionString;
            int      uid    = Convert.ToInt32(Session["CURENT_USER_ID"]);

            /*
             * EmailNotificationsRepository enr = new EmailNotificationsRepository(uid, conStr);
             * response r = enr.UpdateCheckedTimes(Convert.ToDateTime(_timestamp), _d);
             */
            response r = new response(true, null, null, null, null);

            foreach (EmailNotificationExtended ene in EmailNotifications)
            {
                EmailNotification en = new EmailNotification(uid, conStr, Convert.ToInt32(ene.EmailNotification.ID));
                if (en.TIME_CHECKED == null)
                {
                    en.TIME_CHECKED = _d;
                    response rtmp = en.Update();
                    if (!rtmp.Status)
                    {
                        r.AddResponse(rtmp);
                    }
                }
            }
            return(Json(r, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 19
0
        private EEmalNotification EEmailNotification(EmailNotification emailNotification)
        {
            return(new EEmalNotification
            {
                EnableSsl = emailNotification.EnableSsl.Value,
                IsBodyHtml = emailNotification.IsBodyHtml.Value,

                CreatedDate = emailNotification.CreatedDate,
                UpdatedDate = emailNotification.UpdatedDate,

                CreatedBy = emailNotification.CreatedBy,
                EmailNotificationId = emailNotification.EmailNotificationId,
                Port = emailNotification.Port.Value,
                UpdatedBy = emailNotification.UpdatedBy,

                Body = emailNotification.Body,
                Bcc = emailNotification.Bcc,
                CC = emailNotification.CC,
                Host = emailNotification.Host,
                From = emailNotification.From,
                Subject = emailNotification.Subject,
                To = emailNotification.To,
                Username = emailNotification.Username,
            });
        }
Exemplo n.º 20
0
        /// <summary>
        /// Sends the message.
        /// </summary>
        /// <param name="notification">The notification.</param>
        private void SendMessage(EmailNotification notification)
        {
            if (this.notificationSettings.SendEmailEnabled)
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress(this.notificationSettings.EmailSenderName, this.notificationSettings.EmailSenderEmail));
                message.To.Add(new MailboxAddress(notification.ToName, notification.To));
                message.Subject = notification.Subject;
                message.Body    = new TextPart(TextFormat.Html)
                {
                    Text = notification.Body
                };

                using (var client = new SmtpClient())
                {
                    client.Connect(
                        this.notificationSettings.SmtpHost,
                        this.notificationSettings.SmtpPort,
                        this.notificationSettings.SmtpUseSsl);

                    client.Authenticate(this.notificationSettings.SmtpUser, this.notificationSettings.SmtpPassword);

                    client.Send(message);

                    client.Disconnect(true);
                }
            }
        }
        public bool SubmitNewAdjustmentVoucher(List <AdjustmentVoucherViewModel> vmList, string remarks, string requesterID)
        {
            Adjustment_Voucher_Record vourcherRecord = new Adjustment_Voucher_Record();

            vourcherRecord.issueDate       = DateTime.Today;
            vourcherRecord.handlingStaffID = requesterID;
            vourcherRecord.status          = AdjustmentVoucherStatus.PENDING;
            vourcherRecord.remarks         = remarks;

            List <Voucher_Detail> details = new List <Voucher_Detail>();

            foreach (var vm in vmList)
            {
                if (vm.Quantity != 0) // ignore quantity which is equal to 0
                {
                    Voucher_Detail detail = new Voucher_Detail();
                    detail.itemCode    = vm.ItemCode;
                    detail.adjustedQty = vm.Quantity;
                    detail.remarks     = vm.Reason;
                    details.Add(detail);
                }
            }

            vourcherRecord.Voucher_Details = details;
            decimal voucherAmount = GetVoucherRecordTotalAmount(vourcherRecord);

            adjustmentVoucherDAO.AddNewAdjustmentVoucher(vourcherRecord);
            EmailNotification.EmailNotificationForNewAdjustmentVoucher(requesterID, voucherAmount);
            return(true);
        }
Exemplo n.º 22
0
        public NotificationCollection ResetPassword(int userAccountId)
        {
            var result = NotificationCollection.CreateEmpty();

            var userAccount = repository.FindById <UserAccount>(userAccountId);

            if (userAccount.IsNotNull())
            {
                var newPassword = passwordGenerator.NewPassword();
                userAccount.Password = newPassword;
                userAccount.EncrypPassword(passwordEncryptor);

                result += repository.Save(userAccount);

                if (!result.HasErrors())
                {
                    var message = repository.FindBy <EmailTemplate>(e => e.TemplateName == Constants.EmailTemplates.PasswordReset).FirstOrDefault();

                    message.Body = message.Body.Replace(Constants.EmailTemplatePlaceHolders.Password, newPassword);
                    message.Body = message.Body.Replace(Constants.EmailTemplatePlaceHolders.Name, userAccount.FirstName);
                    message.Body = message.Body.Replace(Constants.EmailTemplatePlaceHolders.Username, userAccount.Username);

                    result += repository.Save(EmailNotification.Create(message.Subject, message.Body, SharedConfig.FromSupportEmailAddress, userAccount.EmailAddress));
                }
                if (!result.HasErrors())
                {
                    result += new Notification("Password reset successful.", NotificationSeverity.Information);
                }
            }

            return(result);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Send email
        /// </summary>
        /// <param name="emailNotification"></param>
        /// <param name="cancellationToken"></param>
        public Task SendMailAsync(EmailNotification emailNotification, CancellationToken cancellationToken)
        {
            _logger.LogInformation(_mailOptions.ToString());

            return(emailNotification.IsWithTemplate ? SendEmailTemplateAsync(emailNotification, cancellationToken) :
                   SimpleSendEmailAsync(emailNotification, cancellationToken));
        }
Exemplo n.º 24
0
 public async Task SendMailAsync(EmailNotification notification)
 {
     using (var mail = CreateMessage(notification))
     {
         await _client.SendMailAsync(mail);
     }
 }
Exemplo n.º 25
0
        /// <summary>
        /// Set base notificaiton parameters (sender, recipient, isActive)
        /// </summary>
        /// <param name="notification"></param>
        /// <param name="value"></param>
        private void SetNotificationParameters(EmailNotification notification, OrderChangeEvent value)
        {
            var store = _storeService.GetById(value.ModifiedOrder.StoreId);

            notification.Sender   = store.Email;
            notification.IsActive = true;

            var member = _memberService.GetByIds(new[] { value.ModifiedOrder.CustomerId }).FirstOrDefault();

            if (member != null)
            {
                var email = member.Emails.FirstOrDefault();
                if (!string.IsNullOrEmpty(email))
                {
                    notification.Recipient = email;
                }
            }
            if (string.IsNullOrEmpty(notification.Recipient))
            {
                if (value.ModifiedOrder.Addresses.Count > 0)
                {
                    var address = value.ModifiedOrder.Addresses.FirstOrDefault();
                    if (address != null)
                    {
                        notification.Recipient = address.Email;
                    }
                }
            }
        }
        public async Task <ActionResult> Index(EmailNotification model)
        {
            try
            {
                // Verification
                if (ModelState.IsValid)
                {
                    // Initialization.
                    string emailMsg     = "Dear " + model.ToEmail + ", <br /><br /> Thist is test <b style='color: red'> Notification </b> <br /><br /> Thanks & Regards, <br />Sabarish kumar";
                    string emailSubject = EmailInfo.EMAIL_SUBJECT_DEFAUALT + " Test";

                    // Sending Email.
                    await this.SendEmailAsync(model.ToEmail, emailMsg, emailSubject);


                    // Info.
                    return(this.Json(new { EnableSuccess = true, SuccessTitle = "Success", SuccessMsg = "Notification has been sent successfully! to '" + model.ToEmail + "' Check your email." }));
                }
            }
            catch (Exception ex)
            {
                // Info
                Console.Write(ex);

                // Info
                return(this.Json(new { EnableError = true, ErrorTitle = "Error", ErrorMsg = ex.Message }));
            }

            // Info
            return(this.Json(new { EnableError = true, ErrorTitle = "Error", ErrorMsg = "Something goes wrong, please try again later" }));
        }
Exemplo n.º 27
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            EmailNotification emailNotification = new EmailNotification();

            try
            {
                string subject     = txtCauses.Text;
                string fromAddress = txtEmail.Text.Trim();
                string userName    = "******";
                string pass        = "******";
                string body        = "From: " + fromAddress + "\n";
                body += "Subject: " + subject + "\n";
                body += "Comments: \n" + txtComments.Text + "\n";
                if (EmailNotification.sendEmail(fromAddress, "UserName", "*****@*****.**", "", subject, body, userName, pass))
                {
                    lblMessage.Text = "Success Sending Mail";
                }
                else
                {
                    lblMessage.Text = "Failed to send Mail !";
                }
                lblMessage.ForeColor = System.Drawing.Color.Red;
            }

            catch (Exception ex)
            { throw ex; }
        }
Exemplo n.º 28
0
        private EmailNotification SetDefaultValues(EmailNotification emailNotification)
        {
            return(new EmailNotification
            {
                EnableSsl = (emailNotification.EnableSsl ?? Convert.ToBoolean(ConfigurationManager.AppSettings["EmailNotificationEnableSsl"])),
                IsBodyHtml = emailNotification.IsBodyHtml ?? Convert.ToBoolean(ConfigurationManager.AppSettings["EmailNotificationIsBodyHtml"]),

                CreatedDate = emailNotification.CreatedDate,
                UpdatedDate = emailNotification.UpdatedDate,

                CreatedBy = emailNotification.CreatedBy,
                EmailNotificationId = emailNotification.EmailNotificationId,
                Port = emailNotification.Port ?? Convert.ToInt32(ConfigurationManager.AppSettings["EmailNotificationPort"]),
                UpdatedBy = emailNotification.UpdatedBy,

                Body = emailNotification.Body,
                Bcc = (!string.IsNullOrEmpty(emailNotification.Bcc)) ? emailNotification.Bcc : ConfigurationManager.AppSettings["EmailNotificationBcc"],
                CC = (!string.IsNullOrEmpty(emailNotification.CC)) ? emailNotification.CC : ConfigurationManager.AppSettings["EmailNotificationCC"],
                Host = (!string.IsNullOrEmpty(emailNotification.Host)) ? emailNotification.Host : ConfigurationManager.AppSettings["EmailNotificationHost"],
                From = (!string.IsNullOrEmpty(emailNotification.From)) ? emailNotification.From : ConfigurationManager.AppSettings["EmailNotificationFrom"],
                Password = (!string.IsNullOrEmpty(emailNotification.Password)) ? emailNotification.Password : ConfigurationManager.AppSettings["EmailNotificationPassword"],
                Subject = (!string.IsNullOrEmpty(emailNotification.Subject)) ? emailNotification.Subject : ConfigurationManager.AppSettings["EmailNotificationSubject"],
                To = (!string.IsNullOrEmpty(emailNotification.To)) ? emailNotification.To : ConfigurationManager.AppSettings["EmailNotificationTo"],
                Username = (!string.IsNullOrEmpty(emailNotification.Username)) ? emailNotification.Username : ConfigurationManager.AppSettings["EmailNotificationUsername"],
            });
        }
        public IHttpActionResult Email([FromBody] DTONotificacaoProduto notificacaoProduto)
        {
            try
            {
                EmailNotification         notification      = new EmailNotification();
                NotificacaoProdutoService notifyServ        = new NotificacaoProdutoService();
                DestinarioService         destinarioService = new DestinarioService();
                CrawlerService            crawler           = new CrawlerService();

                var produtosParaNotificar = notifyServ.ListarNotificacoes(notificacaoProduto.EmailDestinario);
                var destinario            = destinarioService.GetDestinario(notificacaoProduto.EmailDestinario);

                List <Produto> listaProdutos = new List <Produto>();

                foreach (var produtos in produtosParaNotificar)
                {
                    var listaProdutosIteracao = crawler.PesquisarProduto(new DTOProdutoPesquisa {
                        produto = produtos.NomeProduto, valor_produto_min = produtos.ValorMinProduto, valor_produto_max = produtos.ValorMaxProduto
                    }).Take(4);
                    listaProdutosIteracao.ForEach(x => listaProdutos.Add(x));
                }

                notification.Notificar(listaProdutos, destinario);
                return(Ok(new {
                    message = "E-mail enviado com sucesso."
                }));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
Exemplo n.º 30
0
        private void SendMailNotify(string BodyMail, string EmailTo)
        {
            try
            {
                logger.Info("SendMailNotify: Start");

                string sSubjectMail = "[Inform] Approve Company User";
                string sBodyMail    = BodyMail;

                EmailNotification email = new EmailNotification();
                email.EmailSubject = sSubjectMail;

                email.EmailSMTP = ConfigurationManager.GetConfiguration().EmailSMTP;
                email.EmailPort = int.Parse(ConfigurationManager.GetConfiguration().EmailPort);
                email.EmailForm = ConfigurationManager.GetConfiguration().EmailFrom;

                ArrayList aEmailTo = new ArrayList();
                aEmailTo.Add(EmailTo);


                email.EmailTo   = aEmailTo;
                email.EmailBody = sBodyMail;

                email.SendEmail();

                logger.Info("SendMailNotify: Complete");
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                logger.Error(ex.StackTrace);
            }
        }
Exemplo n.º 31
0
 public bool SendIssueEmail(EmailNotification emailNotification)
 {
     return mIssueEmailer.SendIssueEmail(emailNotification);
 }
Exemplo n.º 32
0
 public async Task<bool> VendorRegistrationSendToVendor(ParkingSpace parkingSpace)
 {
     var param = new string[] { parkingSpace.Email, parkingSpace.Address };
     var emailToAdminBody = GetMessage(param, System.Web.Hosting.HostingEnvironment.MapPath("~/EmailTemplates/VendorRegistration.html"));
     var emailToAdminReceiver = new List<string>();
     emailToAdminReceiver.Add(parkingSpace.Email);
     var bcc = new List<string>();
     bcc.Add("*****@*****.**");
     var emailToAdmin = new EmailNotification
     {
         From = "*****@*****.**",
         To = emailToAdminReceiver,
         Subject = "Welcome to Parko!",
         Bcc = bcc,
         Message = emailToAdminBody,
         IsHtml = true,
         Status = 1
     };
     await EmailRepository.CreateSync(emailToAdmin);
     return true;
 }
Exemplo n.º 33
0
 public async Task<bool> VendorRegistrationNotification(ParkingSpace parkingSpace)
 {
     var param = new string[] { parkingSpace.Email, parkingSpace.Address };
     var emailToAdminBody = GetMessage(param, System.Web.Hosting.HostingEnvironment.MapPath("~/EmailTemplates/NewVendorRegistration.html"));
     var emailToAdminReceiver = new List<string>();
     emailToAdminReceiver.Add("*****@*****.**");
     emailToAdminReceiver.Add("*****@*****.**");
     emailToAdminReceiver.Add("*****@*****.**");
     var emailToAdmin = new EmailNotification
     {
         From = "*****@*****.**",
         To = emailToAdminReceiver,
         Subject = "Parko - new vendor registration",
         Message = emailToAdminBody,
         IsHtml = true,
         Status = 1
     };
     await EmailRepository.CreateSync(emailToAdmin);
     return true;
 }
Exemplo n.º 34
0
        public bool SendIssueEmail(EmailNotification emailNotification)
        {
            string emailSendEnabledSetting = CommonUtils.GetAppSettingValue(CommonUtils.AppSettingKey.EmailSendEnabled);

            if (emailSendEnabledSetting.ToLower() != "true")
            {
                log.Info("WebConfig setting 'SendEmailEnabled' is set to False.  Exiting SendEmail() method.");
                return false;
            }

            StringBuilder emailTemplate = new StringBuilder();
            string filePath = EmailCommon.GetMailDefinitionFilePath("IssueMailMessageDefinition.html");

            if (!File.Exists(filePath))
            {
                log.Error("Could not find html file for email named '{0}'.", filePath);
                throw new FileNotFoundException(string.Format("Could not find html file for email named '{0}'.", filePath));
            }

            emailTemplate.Append(EmailCommon.ReadEmailTemplate(filePath));

            MailDefinition md = new MailDefinition();

            if (emailNotification.EmailNotificationRule == null)
            {
                log.Info("IssueMailPlugin.SendEmail->No Rule Triggered.");
                return false;
            }

            //TO

            if (emailNotification.SentTo == null || !emailNotification.SentTo.Any())
            {
                log.Error("", "No email recipients could be found with valid email addresses for Sent To field.");
                return false;
            }
            string url = CommonUtils.GetAppSettingValue(CommonUtils.AppSettingKey.ApplicationUrl);
            string issueIdHef = String.Format(@"<a href='{0}?issueid={1}'>{1}</a>", url, emailNotification.IssueId.ToString());

            //{IssueId}
            string token = string.Format("{{{0}}}", IssueEmailSubjectTextTokens.IssueId.ToString());
            emailNotification.Subject = emailNotification.Subject.Replace(token, emailNotification.IssueId.ToString());
            emailNotification.Subject = emailNotification.Subject.Replace(Environment.NewLine, " ").Replace("\r", " ");

            emailNotification.Replacements.Add("<%IssueId%>", issueIdHef);

            emailNotification.Replacements.Add("<%ResponseHistory%>", (BuildResponseHistoryTableHtml(emailNotification.IssueId)));

            emailNotification.Replacements.Add("<%Actions%>", (BuildActionsTableHtml(emailNotification.IssueId)));

            emailNotification.Replacements.Add("<%RelatedDocuments%>", (BuildRelatedDocumentsTableHtml(emailNotification.IssueId)));

            emailNotification.Replacements.Add("<%IssueAttachments%>", (BuildAttachmentsTableHtml(emailNotification.IssueId)));

            emailNotification.Replacements.Add("<%InitialRiskRating%>", BuildHighestRiskText(emailNotification.IssueId, IssuueRiskTypeId.Initial));
            emailNotification.Replacements.Add("<%DoInitialBackgroundColour%>", BuildHighestRiskColourText(emailNotification.IssueId, IssuueRiskTypeId.Initial));

            emailNotification.Replacements.Add("<%FinalRiskRating%>", BuildHighestRiskText(emailNotification.IssueId, IssuueRiskTypeId.Final));
            emailNotification.Replacements.Add("<%DoFinalBackgroundColour%>", BuildHighestRiskColourText(emailNotification.IssueId, IssuueRiskTypeId.Final));

            emailNotification.Replacements.Add("<%DoNothingRiskRating%>", BuildHighestRiskText(emailNotification.IssueId, IssuueRiskTypeId.DoNothing));
            emailNotification.Replacements.Add("<%DoNothingBackgroundColour%>", BuildHighestRiskColourText(emailNotification.IssueId, IssuueRiskTypeId.DoNothing));

            //LatestResponse
            if (emailNotification.HasResponse)
            {
                emailNotification.Replacements.Add("<%LatestResponse%>", BuildLatestIssueResponseText(emailNotification.IssueId));
            }
            else
            {
                emailNotification.Replacements.Add("<%LatestResponse%>", EmailCommon.HtmlEncode("No Response entered."));
            }

            MailMessage message = md.CreateMailMessage(string.Join(",", emailNotification.SentTo.ToArray()), emailNotification.Replacements, emailTemplate.ToString(), new System.Web.UI.Control());

            //FROM
            string emailAdminAccount = CommonUtils.GetAppSettingValue(CommonUtils.AppSettingKey.EmailAdminAccount);
            message.From = new MailAddress(emailAdminAccount);
            message.IsBodyHtml = true;

            //SUBJECT
            message.Subject = emailNotification.Subject;

            IEnumerable<string> cCList = emailNotification.CCList;
            foreach (string addresss in cCList)
            {
                message.CC.Add(new MailAddress(addresss));
            }

            SmtpClient client = new SmtpClient
            {
                Host = CommonUtils.GetAppSettingValue(CommonUtils.AppSettingKey.EmailMailHost)
            };

            try
            {
                //SEND!
                string testEmail = CommonUtils.GetAppSettingValue(CommonUtils.AppSettingKey.EmailDefaultTest);

                if (EmailCommon.IsValidEmailaddress(testEmail))
                {
                    EmailCommon.InterceptEmail(message, testEmail);
                }

                log.Info("Sending email.{0}From = {1}{0}To = {2}{0}Cc = {3}{0}Host = {4}.",
                         Environment.NewLine, message.From, message.To, message.CC, client.Host);

                log.Verbose("{0}", message.Body);

                client.Send(message);
            }
            catch (Exception exception)
            {
                log.Error(exception.Message, exception, "Possible relay error");
                if (exception.InnerException != null)
                {
                    log.Error(exception.InnerException.Message, exception.InnerException, "Possible relay error inner exception.");
                }
            }

            return true;
        }
Exemplo n.º 35
0
 private void StartEmailPlugin(EmailNotification emailNotification)
 {
     //Sends email only if its enable in web.config
     string settingValue = CommonUtils.GetAppSettingValue(CommonUtils.AppSettingKey.EmailSendEnabled);
     if (settingValue.ToLower() == "true")
     {
         var bw = new BackgroundWorker();
         bw.WorkerReportsProgress = false;
         bw.DoWork += bw_PluginDoWork;
         bw.RunWorkerAsync(emailNotification);
     }
 }
Exemplo n.º 36
0
        public EmailNotification GetEmailNotificationObject(IssueModifications issueModifications)
        {
            EmailNotification emailNotification = new EmailNotification();
            emailNotification.IssueId = issueModifications.Issue.Id;

            emailNotification.EmailNotificationRule = CalculateTriggeredIssueNotificationRule(issueModifications);

            if (emailNotification.EmailNotificationRule == null)
            {
                log.Warning("", "Could not sent Issue email notification. Updated Email notification rule needs to be configured and set to Active. Please update under Issue->Config->Email Notifications->Updated.");
            }
            else
            {
                //TEMPLATE
                emailNotification.Replacements = BuildIssueEmailReplacements(issueModifications.Issue);

                string[] sentToTokens = emailNotification.EmailNotificationRule.SendTo.Split(new[] { ',', ';' });
                string[] ccToTokens = emailNotification.EmailNotificationRule.CcTo.Split(new[] { ',', ';' });

                emailNotification.SentTo = BuildIssueEmailRecepientsList(issueModifications, emailNotification.EmailNotificationRule, sentToTokens);

                emailNotification.Subject = BuildIssueSubjectText(issueModifications, emailNotification.EmailNotificationRule.SubjectText);

                emailNotification.CCList = BuildIssueEmailRecepientsList(issueModifications, emailNotification.EmailNotificationRule, ccToTokens);
            }

            return emailNotification;
        }