public PriceNotificationManager()
 {
     BR               = new BaseRepository();
     Logger           = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
     RefreshFrequency = 5;
     EmailEngine      = new EmailEngine();
 }
示例#2
0
        protected void Application_Start()
        {
            log4net.Config.XmlConfigurator.Configure();

            // lazy load DI.
            var logger = ModuleLoader.Dependencies.Get <ILog>("BlogLogger");

            EmailEngine.Logger(logger);

            var diResolver = new DependencyResolver(ModuleLoader.Dependencies);

            System.Web.Mvc.DependencyResolver.SetResolver(diResolver);         // MVC
            GlobalConfiguration.Configuration.DependencyResolver = diResolver; // WebAPI

            // To resolve self referencing loop error.
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Re‌ferenceLoopHandling = ReferenceLoopHandling.Ignore;

            WebApiConfig.Register(GlobalConfiguration.Configuration);

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            GlobalConfiguration.Configuration.EnsureInitialized();
        }
示例#3
0
        public ActionResult RegisterUser(RegisterUserViewModel userViewModel)
        {
            ResponseOut responseOut = new ResponseOut();

            IUserBL  userBL  = new UserEngine();
            IEmailBL emailBL = new EmailEngine();

            try
            {
                if (userViewModel != null)
                {
                    responseOut = userBL.RegisterUser(userViewModel);
                    string body   = this.createEmailBody(responseOut.hash);
                    bool   status = Utilities.SendEmail("", responseOut.email, "Codelate | Verify your Email!", body, 587, true, "smtp.gmail.com", "", null, null);
                    if (status)
                    {
                    }
                }
                else
                {
                    responseOut.message = ActionMessage.ProbleminData;
                    responseOut.status  = ActionStatus.Fail;
                }
            }
            catch (Exception ex)
            {
                responseOut.message = ActionMessage.ApplicationException;
                responseOut.status  = ActionStatus.Fail;
            }
            return(Json(responseOut, JsonRequestBehavior.AllowGet));
        }
        /// <summary>
        /// Sends an alert to all registered recipients in a franchise for a given event.  THIS FUNCTION
        /// SWALLOWS EXCEPTIONS.
        /// </summary>
        /// <param name="alertType">The type of alert to send.</param>
        /// <param name="franchiseId">The franchiseId to use when getting the list of recipients to send to.</param>
        /// <returns>a boolean indicating whether emails were successfully sent.  Also returns true if no alerts are found.</returns>
        ///
        public bool SendAlert(AlertType alertType, int franchiseId)
        {
            try
            {
                var type   = (int)alertType;
                var toSend = new List <MailMessage>();

                using (var ctx = new EightHundredEntities(UserKey))
                {
                    var alerts = (from a in ctx.tbl_OwnerAlerts
                                  join d in ctx.tbl_OwnerAlertDestinations
                                  on a.OwnerAlertId equals d.OwnerAlertId
                                  join t in ctx.tbl_OwnerAlertCommunicationTypes
                                  on d.OwnerAlertCommunicationTypeID equals t.OwnerAlertCommunicationTypeId
                                  where a.FranchiseID == franchiseId &&
                                  a.OwnerAlertTypeId == type &&
                                  d.OwneralertEnabledYN &&
                                  a.OwneralertEnabledYN
                                  select
                                  new
                    {
                        Subject = a.Subject,
                        Body = a.Descriptions,
                        Address = d.OwnerAlertDestinationText,
                        Type = d.OwnerAlertCommunicationTypeID,
                        DestText = d.OwnerAlertDestinationAdditionalText
                    }).GroupBy(g => new { g.Subject, g.Body })
                                 .ToDictionary(g => g.Key, g => string.Join(",", g.Select(m => BuildAddress(m.Address, m.DestText, (AlertDestinationType)m.Type)).ToArray()));

                    if (alerts.Count == 0)
                    {
                        return(true);
                    }

                    foreach (var pair in alerts)
                    {
                        var msg = new MailMessage();
                        msg.To.Add(pair.Value);
                        msg.Subject = pair.Key.Subject;
                        msg.Body    = pair.Key.Body;
                        toSend.Add(msg);
                    }
                }

                var engine  = new EmailEngine();
                var allSent = toSend.Select(engine.Send).All(r => r);

                if (!allSent)
                {
                    //TODO: Log info that some alerts could not be sent.
                }

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
示例#5
0
        public void TestEmailEngine()
        {
            EmailEngine ee   = new EmailEngine();
            User        user = new User();

            user.Email = "*****@*****.**";
            ee.SendEmail(user);
        }
示例#6
0
 public static void ForceEngineHeartbeats()
 {
     EmailEngine.ForceHeartbeat();
     WebEmailEngine.ForceHeartbeat();
     ReportEngine.ForceHeartbeat();
     WebReportEngine.ForceHeartbeat();
     RssEventEngine.ForceHeartbeat();
     WebRssEventEngine.ForceHeartbeat();
 }
示例#7
0
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="options">邮件选项信息</param>
        /// <returns>发送结果</returns>
        public static async Task <EmailResult> SendAsync(params EmailOption[] options)
        {
            if (EmailEngine == null)
            {
                throw new Exception("没有配置任何的邮件发送执行器");
            }
            Dictionary <string, List <EmailOption> > emailOptionGroup = new Dictionary <string, List <EmailOption> >();
            Dictionary <string, EmailAccount>        accounts         = new Dictionary <string, EmailAccount>();

            #region 获取服务器信息

            foreach (var option in options)
            {
                var emailAccounts = GetAccounts(option);
                foreach (var account in emailAccounts)
                {
                    string accountKey = account.IdentityKey;
                    if (accounts.ContainsKey(accountKey))
                    {
                        emailOptionGroup[accountKey].Add(option);
                    }
                    else
                    {
                        emailOptionGroup.Add(accountKey, new List <EmailOption>()
                        {
                            option
                        });
                        accounts.Add(accountKey, account);
                    }
                }
            }

            #endregion

            EmailResult result = new EmailResult()
            {
                Message = "发送成功",
                Success = true
            };

            #region 执行

            foreach (var optionGroup in emailOptionGroup)
            {
                var account     = accounts[optionGroup.Key];
                var exectResult = await EmailEngine.SendAsync(account, optionGroup.Value.ToArray()).ConfigureAwait(false);

                if (!exectResult.Success)
                {
                    result = exectResult;
                }
            }

            #endregion

            return(result);
        }
    protected void Button1_Click(object sender, EventArgs e)
    {
        // Generate a new 12-character password with 1 non-alphanumeric character.
        string password = Membership.GeneratePassword(6, 0);
        string username = fname.Text + "." + lname.Text;
        EmailEngine emailSender = new EmailEngine();
        try
        {
            // Create new user.
            
            MembershipUser newUser = Membership.CreateUser(username, password, email.Text);
            
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["collabacklogConnectionString"].ToString());
            conn.Open();
            SqlCommand comm = new SqlCommand();
            comm.CommandText = "Select employeeID from aspnet_users where username = '******'";
            comm.Connection = conn;
            //Get EmployeeID Generated
            int employeeID = Convert.ToInt32(comm.ExecuteScalar().ToString());
            //
            comm.CommandText = "Update aspnet_users set fname = '" + fname.Text.ToString() + "', sname = '" + lname.Text.ToString() + "', mname ='"+ mname.Text.ToString() +"'  where employeeID = " + employeeID;
            comm.ExecuteNonQuery();

            //Send Users Login Credential
            comm.CommandText = "EXEC proc_newusersmail  @employeeID , @password";
            comm.Parameters.AddWithValue("@employeeID", employeeID);
            comm.Parameters.AddWithValue("@password", password);
            comm.ExecuteNonQuery();

            /*
            Msg.Text = "User <b>" + Server.HtmlEncode(username) + "</b> created. " +
                       "Your temporary password is " + password;

            String emailBody = "Dear " + Server.HtmlEncode(username) + "<br/> You have been registered on the Collateral Portal, below are your credentials. <br/> " +
          "User Name: <b>" + Server.HtmlEncode(username) + "</b> . " +
                     "Password: <b>d" + password + "</b>. <br/><p> However you are required to login <a href='http://mobileserver1/collabacklogVS/account/login.aspx'> Here</a> to change your password. Thank you.</p>";

            emailSender.send(email.Text, "Collateral App Login Credentials", emailBody);
            */

        }
        catch (MembershipCreateUserException ex)
        {
            Msg.Text = GetErrorMessage(ex.StatusCode);
        }
        catch (HttpException exx)
        {
            Msg.Text = exx.Message;
        }
    }
示例#9
0
        public JsonResult ContactUs(EmailContactUsViewModel data)
        {
            ResponseOut responseOut = new ResponseOut();
            IEmailBL    emailBL     = new EmailEngine();

            try
            {
                //int user_id = Convert.ToInt32(HttpContext.Session[SessionKey.CurrentUserID]);
                responseOut = emailBL.ContactUsEmail(data);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(Json(responseOut, JsonRequestBehavior.AllowGet));
        }
示例#10
0
        /// <summary>
        /// Email the error to technical support
        /// </summary>
        /// <returns></returns>
        private bool SendError()
        {
            string      body;
            string      subject     = "Error in " + myErrorInformation.ProgramName;
            string      attachments = string.Empty;
            EmailEngine email       = new EmailEngine();


            try
            {
                ValidateChildren();

                if (epValidation.GetError(txtSteps).Length == 0)
                {
                    //Send using mailto link if there is no smtp server specified
                    if (myErrorInformation.SmtpServer == string.Empty)
                    {
                        TryLink(myErrorInformation.GetManualEmailMessage());

                        return(true);
                    }

                    //Send using smtp server
                    email.ServerName         = myErrorInformation.SmtpServer;
                    myErrorInformation.Steps = txtSteps.Text;
                    body         = myErrorInformation.GetXMLMessage();
                    attachments += myErrorInformation.ScreenShot + ",";
                    attachments += myErrorInformation.EventLogText + ",";

                    email.SendMail(myErrorInformation.Email, myErrorInformation.SupportEmail, subject, body, attachments);
                    return(true);
                }

                MessageBox.Show(this, epValidation.GetError(txtSteps), "Errors on Screen", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return(false);
            }
            catch (Exception ex)
            {
                //Smtp server send failed, send with a mailto link
                GuiException.HandleException(ex);
                TryLink(myErrorInformation.GetManualEmailMessage());
                return(false);
            }
        }
示例#11
0
        /// <summary>
        ///     Execute all the services
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DoWork(object sender, DoWorkEventArgs e)
        {
            Logger.Info("starting irc");

            if (Config.GetBoolValue(Globals.YokXmlUseirc))
            {
                if (!IrcEngine.GetInstance().Start())
                {
                    Logger.Error("Irc start failed");
                }
            }
            else
            {
                if (!IrcEngine.GetInstance().Stop())
                {
                    Logger.Error("Irc stop failed");
                }

                Logger.Info("IRC DISABLED");
            }

            Logger.Info("starting email");

            if (Config.GetBoolValue(Globals.YokXmlUseemail))
            {
                if (ScheduleEngine.Check())
                {
                    if (!EmailEngine.Send())
                    {
                        Logger.Error("Email send failed");
                    }
                }
                else
                {
                    Logger.Info("Data not ready to send");
                }
            }
            else
            {
                Logger.Info("EMAIL DISABLED");
            }
        }
示例#12
0
        public ActionResult Contact(ContactViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var title   = "Message for GuruIn.NET";
                    var subject = string.Format("Message from {0} for GuruIn.NET", model.Name);

                    var template = EmailEngine.GetTemplate("contact-us-template");
                    var body     = template.Replace("*|MC:TITLE|*", title)
                                   .Replace("*|MC:SUBJECT|*", subject)
                                   .Replace("*|MC:EMAILTOBROWSERLINK|*", "http://www.GuruIn.NET")
                                   .Replace("{0}", model.Name)
                                   .Replace("{1}", model.Email)
                                   .Replace("{2}", model.Message.Replace("\r\n", "<br/>").Replace("\n", "<br/>").Replace("\r", "<br/>"))
                                   .Replace("*|CURRENT_YEAR|*", DateTime.Now.Year.ToString())
                                   .Replace("*|LIST:COMPANY|*", "GuruIn.NET");

                    var fromTo = ConfigManager.Get <string>("SmtpUserName");

                    var result = EmailEngine.SendEmail(fromTo, "GuruIn.NET", fromTo, subject, subject, body, cc: (model.CopyUser && !string.IsNullOrWhiteSpace(model.Email) ? model.Email : null));
                    if (result)
                    {
                        Session["USER_MESSAGE"]          = "Your message has been successfully sent. Thank you.";
                        Session["USER_MESSAGE_SEVERITY"] = "Success";
                        Session["USER_MESSAGE_TITLE"]    = "Message Sent";

                        return(RedirectToAction("Index"));
                    }
                }
                catch (Exception ex)
                {
                    Session["USER_MESSAGE"]          = "Sorry, there was an error sending the message. Please try again later.";
                    Session["USER_MESSAGE_SEVERITY"] = "Error";

                    _log.Error("HomeController - Contact", ex);
                }
            }

            return(View(model));
        }
        private bool NotifyNewComment(Comment newComment, int postId)
        {
            try
            {
                var domain      = Request.Url.OriginalString.Replace(Request.Url.PathAndQuery, string.Empty);
                var postLink    = domain + "/Blog/Post/" + postId;
                var commentLink = domain + "/Blog/Post/" + postId + "#comment-" + newComment.Id;
                var deleteLink  = domain + "/Blog/DeleteComment/" + newComment.Id + "/" + DeleteCommentCode + "?postId=" + postId;

                var title   = "New Comment on GuruIn.NET Blog";
                var subject = "Review a new comment on GuruIn.NET Blog";

                var template = EmailEngine.GetTemplate("new-comment-template");
                var body     = template.Replace("*|MC:TITLE|*", title)
                               .Replace("*|MC:SUBJECT|*", subject)
                               .Replace("*|MC:EMAILTOBROWSERLINK|*", "http://www.GuruIn.NET")
                               .Replace("{0}", newComment.Name)
                               .Replace("{1}", newComment.Email)
                               .Replace("{2}", newComment.Content.Replace("\r\n", "<br/>").Replace("\n", "<br/>").Replace("\r", "<br/>"))
                               .Replace("{3}", postLink)
                               .Replace("{4}", commentLink)
                               .Replace("{5}", deleteLink)
                               .Replace("*|CURRENT_YEAR|*", DateTime.Now.Year.ToString())
                               .Replace("*|LIST:COMPANY|*", "GuruIn.NET");

                var fromTo = ConfigManager.Get <string>("SmtpUserName");

                var result = EmailEngine.SendEmail(fromTo, "GuruIn.NET", fromTo, subject, subject, body);
                return(result);
            }
            catch (Exception ex)
            {
                _log.Error("BlogsController - NotifyNewComment", ex);
                return(false);
            }
        }
示例#14
0
        public OperationResult <bool> SendTechnicianBio(int techId, string recipients)
        {
            var result = new OperationResult <bool>();

            try
            {
                var renderResult = GetBioInternal(techId, false);

                if (!renderResult.Success)
                {
                    result.Message = renderResult.Message;
                    return(result);
                }

                var e         = new EmailEngine();
                var cacheItem = BioCache[techId];
                using (var s = new MemoryStream(cacheItem.Data))
                {
                    s.Seek(0, SeekOrigin.Begin);
                    s.Position = 0;

                    var att = new Attachment(s, cacheItem.FileName, "application/pdf");
                    e.Send(null, recipients, null, null, "Technician Bio", "", new[] { att }, true);
                }

                result.Success    = true;
                result.ResultData = true;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
                result.Success = false;
            }

            return(result);
        }
示例#15
0
        private void SendRegistrationAlert(string UserName, string amt, string mn, string yr)
        {
            string body = PopulateMailBody(UserName, amt, mn, yr);

            EmailEngine.SendMail(UserName, "Welcome to ABC HRMS.", body);
        }
        public OperationResult <bool> SendToCustomer(int id, string to)
        {
            var result  = new OperationResult <bool>();
            var invoice = TransformJobToInvoice(id);

            if (invoice == null)
            {
                result.Success    = false;
                result.ResultData = false;
                result.Message    = string.Format("Job '{0}' not found.", id);
                return(result);
            }

            var client        = GetInvoiceGen();
            var genResultPdf  = GetInvoiceInternal(id);
            var genResultHtml = client.RenderHtml(invoice);
            var docType       = invoice.IsEstimate ? "Estimate" : "Invoice";

            if (!genResultPdf.Success || !genResultHtml.Success)
            {
                result.Success    = false;
                result.ResultData = false;
                result.Message    = string.Format("Could not send {0} to customer: {1}", docType, (genResultPdf.Message ?? genResultHtml.ExceptionMessage));
                return(result);
            }

            var html    = Encoding.Unicode.GetString(genResultHtml.Data);
            var engine  = new EmailEngine();
            var subject = string.Format("{0} - {1}", docType, id);
            var from    = invoice.FranchiseTypeID == 6
                ? GlobalConfiguration.PlumberInvoiceFromAddress
                : GlobalConfiguration.ConnectUsProInvoiceFromAddress;


            //Do not send invoices to customers when running in test mode.
            if (GlobalConfiguration.TestMode)
            {
                to = string.Empty;
            }

            bool sent;

            using (var data = new MemoryStream(genResultPdf.ResultData.Value))
            {
                sent = engine.Send(from, to, null, GlobalConfiguration.InvoiceSendBcc, subject, html,
                                   new[] { new Attachment(data, genResultPdf.ResultData.Key) },
                                   true);
            }

            result.Success = sent;

            if (!result.Success)
            {
                result.Message = string.Format("The {0} failed to send.", docType);
            }
            else
            {
                MarkInvoiced(id, DateTime.Now);
            }

            return(result);
        }
示例#17
0
        protected void Session_End(object sender, EventArgs e)
        {
            //we are going to put this here for now, as the push email may not yet be working.
            //get locator
            DBLocator myDBLocator = (DBLocator)Application["myDBLocator"];
            WebSiteConfigInfo myWebSiteConfigInfo = (WebSiteConfigInfo)Application["mySiteConfigInfo"];
            using (DBContext myDBContext = new DBContext(myDBLocator))
            {
                EmailEngine myEmailEngine = new EmailEngine(myDBContext, new External.EmailYak(myWebSiteConfigInfo.EmailYak_Domain, myWebSiteConfigInfo.EmailYak_BaseURL, myWebSiteConfigInfo.EmailYak_CallBackURL, myWebSiteConfigInfo.EmailYak_IsPushEmail, myWebSiteConfigInfo.EmailYak_MessageFooter));
                int i = myEmailEngine.GetAllNewAndForward();
                if (i > 0)
                    myDBContext.Logger.LogInformation(string.Format("{0} Message forwarding during Session End", i), LogPriority.Normal);
            }

            try
            { ((WebSiteSession)Session["mySession"]).End(); }
            catch { }
        }
示例#18
0
        private void SendRegistrationAlert(string UserName, string Email)
        {
            string body = PopulateMailBody(UserName, Email);

            EmailEngine.SendMail(Email, "Welcome to ABC HRMS.", body);
        }
示例#19
0
        public HttpResponseMessage Post([FromBody] ContactModel model)
        {
            HttpResponseMessage responseMessage = new HttpResponseMessage();

            responseMessage.StatusCode = HttpStatusCode.OK;

            #region Field Validation

            ErrorsManager errorsManager = new ErrorsManager();
            if (string.IsNullOrEmpty(model.FirstName))
            {
                errorsManager.AddError(new ValidationException("First name is empty.", "FirstName"));
            }
            if (string.IsNullOrEmpty(model.LastName))
            {
                errorsManager.AddError(new ValidationException("Last name is empty.", "LastName"));
            }
            if (string.IsNullOrEmpty(model.Company))
            {
                errorsManager.AddError(new ValidationException("Company is empty.", "Company"));
            }

            if (errorsManager.HasErrors)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(errorsManager.ToValidationString())
                });
            }
            #endregion
            try
            {
                ContactUsOpsMgmt.InsertItem(model.FirstName, model.LastName, model.Address, model.Address2, model.Company,
                                            model.City, model.State, model.Zip, model.Company, model.Phone, model.Message, model.ReasonsForContact, model.HasOptedForSubscription);

                EmailEngine emailEngine = new EmailEngine(string.Empty, "ContactTemplate", "A new contact request has been submitted.");
                emailEngine.AddAdminReceivers();
                emailEngine.AddMergingField("FirstName", model.FirstName);
                emailEngine.AddMergingField("LastName", model.LastName);
                emailEngine.AddMergingField("Address", model.Address);
                emailEngine.AddMergingField("Address2", model.Address);
                emailEngine.AddMergingField("Company", model.Company);
                emailEngine.AddMergingField("City", model.City);
                emailEngine.AddMergingField("State", model.State);
                emailEngine.AddMergingField("Zip", model.Zip);
                emailEngine.AddMergingField("Phone", model.Phone);
                emailEngine.AddMergingField("Country", model.Country);
                emailEngine.AddMergingField("Message", model.Message);
                emailEngine.AddMergingField("ReasonsForContact", model.ReasonsForContact);
                emailEngine.AddMergingField("HasOptedForSubscription", model.HasOptedForSubscription);


                emailEngine.SendEmail();

                return(responseMessage);
            }
            catch (Exception ex)
            {
                Log.Write(ex, System.Diagnostics.TraceEventType.Error);
                errorsManager.AddError(new ValidationException("Unknown error has occured.", "General"));
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(errorsManager.ToValidationString())
                });
            }
        }
示例#20
0
        public static void SendMessage(
            string fromAddress,
            string fromDisplayName,
            string toAddress,
            string toDisplayName,
            string subject,
            string body,
            string replyToAddress,
            string replyToDisplayName,
            string ccAddress,
            string ccDisplayName,
            EmailEngine ee,
            bool isHtml       = true,
            bool sendAsync    = false,
            bool throwOnError = true
            )
        {
            if (string.IsNullOrEmpty(toAddress) || string.IsNullOrEmpty(fromAddress))
            {
                throw new Exception("to or from were empty");
            }
            else
            {
                switch (ee)
                {
                //case EmailEngine.MailMergeLib:
                //  #region
                //  var mmm = new MailMergeMessage();

                //  mmm.MailMergeAddresses.Add(new MailMergeAddress(MailAddressType.From, fromAddress, fromDisplayName, Encoding.UTF8));
                //  mmm.MailMergeAddresses.Add(new MailMergeAddress(MailAddressType.To, toAddress, toDisplayName, Encoding.UTF8));

                //  mmm.Subject = subject.Trim();
                //  mmm.HtmlText = body;
                //  mmm.PlainText = mmm.ConvertHtmlToPlainText();

                //  mmm.CultureInfo = new System.Globalization.CultureInfo("en-US");
                //  mmm.CharacterEncoding = Encoding.UTF8;
                //  mmm.TextTransferEncoding = System.Net.Mime.TransferEncoding.Base64;
                //  mmm.BinaryTransferEncoding = System.Net.Mime.TransferEncoding.Base64;

                //  SendMessage(mmm, sendAsync, throwOnError);
                //  #endregion
                //  break;
                //case EmailEngine.Chilkat:
                //  #region
                //  var e = new Chilkat.Email();

                //  e.Body = body;
                //  e.Subject = subject;
                //  e.AddTo(toDisplayName, toAddress);
                //  e.FromAddress = fromAddress;
                //  e.FromName = fromDisplayName;

                //  SendMessage(e, sendAsync, throwOnError);
                //  #endregion
                //  break;
                case EmailEngine.DotNet:
                    #region
                    MailMessage mm = new MailMessage();

                    mm.From            = new MailAddress(fromAddress, fromDisplayName, System.Text.Encoding.UTF8);
                    mm.Subject         = subject.Trim();
                    mm.SubjectEncoding = System.Text.Encoding.UTF8;
                    mm.Body            = body;
                    mm.IsBodyHtml      = isHtml;
                    mm.BodyEncoding    = System.Text.Encoding.UTF8;
                    //mm.PlainText = mmm.ConvertHtmlToPlainText();

                    #region handle comma delimeted TO
                    if (toAddress.Contains(","))
                    {
                        //Split mult. comma delim to Addresses
                        string[] saTo = toAddress.Split((new char[] { ',', ';' }), StringSplitOptions.RemoveEmptyEntries);

                        foreach (string sTempToAddress in saTo)
                        {
                            mm.To.Add(new MailAddress(sTempToAddress));
                        }
                    }
                    else
                    {
                        //One To Address
                        mm.To.Add(new MailAddress(toAddress, toDisplayName, System.Text.Encoding.UTF8));
                    }
                    #endregion

                    if (!string.IsNullOrEmpty(replyToAddress))
                    {
                        mm.ReplyToList.Add(new MailAddress(replyToAddress, replyToDisplayName, System.Text.Encoding.UTF8));
                    }

                    if (!string.IsNullOrEmpty(ccAddress))
                    {
                        mm.CC.Add(new MailAddress(ccAddress, ccDisplayName, System.Text.Encoding.UTF8));
                    }

                    SendMessage(mm, sendAsync, throwOnError);
                    #endregion
                    break;
                }
            }
        }
        public HttpResponseMessage Post([FromBody] ImageSubmissionModel model)
        {
            HttpResponseMessage responseMessage = new HttpResponseMessage();

            responseMessage.StatusCode = HttpStatusCode.OK;

            #region Field Validation

            ErrorsManager errorsManager = new ErrorsManager();
            if (string.IsNullOrEmpty(model.FullName))
            {
                errorsManager.AddError(new ValidationException("Name is empty.", "FullName"));
            }
            if (string.IsNullOrEmpty(model.Company))
            {
                errorsManager.AddError(new ValidationException("Company is empty.", "Company"));
            }
            if (string.IsNullOrEmpty(model.Email))
            {
                errorsManager.AddError(new ValidationException("Email is empty.", "Email"));
            }
            else
            {
                if (!(Regex.IsMatch(model.Email, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase)))
                {
                    errorsManager.AddError(new ValidationException("Email is not valid.", "Email"));
                }
            }
            if (errorsManager.HasErrors)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(errorsManager.ToValidationString())
                });
            }
            #endregion
            try
            {
                ImageSubmissionOpsMgmt.InsertItem(model.FullName, model.Company, model.PhoneNumber, model.Email, model.Comments);

                EmailEngine emailEngine = new EmailEngine(string.Empty, "ImageSubmissionTemplate", "A new image upload request has been submitted.");
                emailEngine.AddAdminReceivers();
                emailEngine.AddMergingField("FullName", model.FullName);
                emailEngine.AddMergingField("Company", model.Company);
                emailEngine.AddMergingField("PhoneNumber", model.PhoneNumber);
                emailEngine.AddMergingField("Email", model.Email);
                emailEngine.AddMergingField("Content", model.Comments);


                emailEngine.SendEmail();

                return(responseMessage);
            }
            catch (Exception ex)
            {
                Log.Write(ex, System.Diagnostics.TraceEventType.Error);
                errorsManager.AddError(new ValidationException("Unknown error has occured.", "General"));
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(errorsManager.ToValidationString())
                });
            }
        }