protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            int emailID = Convert.ToInt32(Request.QueryString["emailID"]);

            // create object
            qCom_EmailTool email = new qCom_EmailTool(emailID);

            qPtl_User user = new qPtl_User(Convert.ToInt32(Context.Items["UserID"]));
            txtEmail.Text = user.Email;

            lblSubject.Text = email.emailSubject;

            // get headers and footers
            string query = "SELECT TOP(1) * FROM qCom_EmailPreferences WHERE Available = 'Yes'";
            qDbs_SQLcode sql = new qDbs_SQLcode();
            SqlDataReader eReader = sql.GetDataReader(query);

            eReader.Read();
            string header = Convert.ToString(eReader["Header"]);
            string footer = Convert.ToString(eReader["Footer"]);
            string unsubscribe = Convert.ToString(eReader["Unsubscribe"]);
            eReader.Close();

            // if email type is bulk, then add footer
            string completeMessage = header + email.emailDraft + footer;
            if (email.emailType == "bulk")
            {
                completeMessage += unsubscribe;
            }

            lblBody.Text = completeMessage;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Request.QueryString["htmlSource"]) && !string.IsNullOrEmpty(Request.QueryString["pdfOutput"]))
        {
            string host_url = Request.QueryString["htmlSource"];
            string file_out = string.Format("{0}{1}", Server.MapPath(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["Site_PdfOutput"])), Request.QueryString["pdfOutput"]);

            var authentication_cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

            var sb_parameters = new StringBuilder();

            HtmlToPdfConverter converter = new HtmlToPdfConverter();

            converter.ConvertFromUrl(host_url,
                                     file_out,
                                     new HtmlToPdfConverterOptions
                                     {
                                         Orientation = "portrait",
                                         CookieName = authentication_cookie.Name,
                                         CookieValue = authentication_cookie.Value
                                     });

            // EMAIL PDF
            int email_id = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Members_InvitationEmailID"]);
            string email_address = Convert.ToString(Request.QueryString["emailAddress"]);

            Quartz.Communication.qCom_EmailTool email = new Quartz.Communication.qCom_EmailTool(email_id);

            qPtl_User user = new qPtl_User(Convert.ToInt32(Context.Items["UserID"]));
            email.SendDatabaseMailWithAttachment(email_address, email_id, user.UserID, "", "", "", file_out);

            string message = "* Email Successfully Sent";

            // DELETE FILE
            //File.Delete(file_out);

            // REDIRECT
            if (!String.IsNullOrEmpty(Request.QueryString["returnURL"]))
            {
                //Session.Abandon();
                //FormsAuthentication.SignOut();
                Response.Redirect(Request.QueryString["returnURL"]);
            }
            else
                Response.Redirect("~/qPtl/invitation-email.aspx?message=" + message + "&file=" + file_out);

            /*
            Response.ContentType = string.Format("application/{0}", Path.GetExtension(file_out).Trim('.'));
            Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", Path.GetFileName(file_out)));
            Response.TransmitFile(file_out);
            Response.Flush();

            File.Delete(file_out);
            */

        }
    }
        public void SendNotification(int emailID, int UserID, int ProfileUserID, string comment, int ReferenceID)
        {
            qCom_EmailTool email = new qCom_EmailTool();

            qPtl_User user           = new qPtl_User(ProfileUserID);
            qPtl_User commentingUser = new qPtl_User(UserID);

            if (!string.IsNullOrEmpty(user.Email))
            {
                email.SendDatabaseMail(user.Email, emailID, user.UserID, commentingUser.UserName, comment, ReferenceID.ToString(), string.Empty, string.Empty, false);
            }
        }
    protected void sendNow()
    {
        int emailID = Convert.ToInt32(Request.QueryString["emailID"]);

        // create object
        qCom_EmailTool email = new qCom_EmailTool(emailID);

        qPtl_User user = new qPtl_User(Convert.ToInt32(Context.Items["UserID"]));

        email.SendDatabaseMail(txtEmail.Text, Convert.ToInt32(Request.QueryString["emailID"]), user.UserID, user.UserName, txtValue1.Text, txtValue2.Text, txtValue3.Text, txtValue4.Text, false);

        lblMessage.Text = "* Email Successfully Sent";
        lblMessage.Visible = true;
    }
    protected void btnApproveRequest_Click(object sender, EventArgs e)
    {
        qOrg_GroupRequests request = new qOrg_GroupRequests(Convert.ToInt32(Request.QueryString["groupRequestID"]));
        qPtl_User user = new qPtl_User(Convert.ToInt32(Context.Items["UserID"]));
        request.ApprovedBy = user.UserName;
        request.WhenApproved = DateTime.Now;
        request.Status = "Pending-WaitingPrincipalApproval";
        request.Update();

        // send email to principal
        int principal_email_id = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["GroupRequest_principal_EmailID"]);
        qCom_EmailTool email = new qCom_EmailTool(principal_email_id);
        string principal_name = request.PrincipalRole + " " + request.PrincipalLastName;
        email.SendDatabaseMail(request.PrincipalEmail, principal_email_id, 0, request.GroupShortName, request.GroupShortName, request.WhyJoin, Convert.ToString(request.GroupRequestID), principal_name, false);

        Response.Redirect(Request.Url.ToString());
    }
    protected void btnRequestPasswordReset_Click(object sender, EventArgs e)
    {
        var user = qPtl_User.GetUserByEmail(txtOrigEmail.Text);

        if (user != null)
        {
            if (user.UserID > 0)
            {
                if (user.SetPasswordResetCode(user.UserID))
                {
                    // create object
                    int emailID = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Email_ForgotPasswordID"]);
                    qCom_EmailTool email = new qCom_EmailTool(emailID);

                    qPtl_User updated_user = new qPtl_User(user.UserID);

                    int sent_email_log_id = email.SendDatabaseMail(updated_user.Email, emailID, updated_user.UserID, updated_user.UserName, updated_user.PasswordResetCode, Request.Url.Authority + HttpRuntime.AppDomainAppVirtualPath.TrimEnd('/'), string.Empty, string.Empty, false);

                    if (sent_email_log_id > 0)
                    {
                        lblMsgRequest.Text = "<br>Please check your email for further instructions";
                        txtOrigEmail.Visible = false;
                        btnRequestPasswordReset.Visible = false;
                        hplCancelRequest.Visible = false;
                    }
                    else
                    {
                        lblMsgRequest.Text = "<br><br>An error occured sending an email, please contact support";
                    }
                }
                else
                {
                    lblMsgRequest.Text = "<br><br>An error occured setting the reset code, please contact support";
                }
            }
        }
        else
            lblMsgRequest.Text = "<br><br>Email address not found";
    }
        //Send to just one address with text replacement
        public int SendDatabaseMail(string address, int emailID, int userID, string userName, string value1, string value2, string value3, string value4, bool no_duplicates_today)
        {
            // get email info
            qCom_EmailTool email      = new qCom_EmailTool(emailID);
            qCom_EmailItem full_email = new qCom_EmailItem(emailID);

            string header              = string.Empty;
            string footer              = string.Empty;
            string strFromEmail        = string.Empty;
            string fromName            = string.Empty;
            string emailUsername       = null;
            string emailPassword       = null;
            string emailServer         = null;
            bool   sslEnabled          = false;
            int    portNum             = 0;
            string strDID              = string.Empty;
            int    return_email_log_id = 0;
            bool   passed_send_checks  = false;
            bool   already_sent_today  = true;
            string returnedEmail       = string.Empty;
            bool   ok_to_send          = false;
            string noEmail             = string.Empty;


            // Check to see if email already sent to user today
            if (no_duplicates_today == true)
            {
                var prior_current_day_log = qCom_EmailLog.CheckForEmailSentLastDay(address);

                if (prior_current_day_log == null)
                {
                    already_sent_today = false;
                }
            }
            else
            {
                already_sent_today = false;
            }

            qCom_UserPreference_View u_pref = new qCom_UserPreference_View(address);

            if (u_pref.UserID > 0)
            {
                if (u_pref.OkBulkEmail == "Yes" || u_pref.OkEmail == "Yes")
                {
                    ok_to_send = true;
                }
            }
            else
            {
                ok_to_send = true;
            }

            if (already_sent_today == false && ok_to_send == true)
            {
                passed_send_checks = true;
            }
            else
            {
                passed_send_checks = false;
            }

            qPtl_User user = new qPtl_User(Convert.ToInt32(userID));

            if (user.UserID == 0)
            {
                user.Email     = "";
                user.FirstName = "";
                user.LastName  = "";
            }

            // load default email preferences
            if (String.IsNullOrEmpty(emailServer))
            {
                var email_pref = qCom_EmailPreference.GetEmailPreferences();

                if (email_pref != null)
                {
                    if (email_pref.EmailPreferencesID > 0)
                    {
                        header        = email_pref.Header;
                        footer        = email_pref.Footer;
                        strFromEmail  = email_pref.FromEmailAddress;
                        fromName      = email_pref.FromName;
                        emailServer   = email_pref.SMTPServer;
                        emailUsername = email_pref.SMTPUsername;
                        emailPassword = email_pref.SMTPPassword;
                        sslEnabled    = email_pref.SMTPSSL;
                        portNum       = email_pref.SMTPPort;
                    }
                }
            }

            // format as friendly send address
            string strFullEmail = string.Empty;

            if (!String.IsNullOrEmpty(fromName))
            {
                strFullEmail = fromName + " <" + strFromEmail + ">";
            }
            else
            {
                strFullEmail = strFromEmail;
            }

            string messageBody = header;

            messageBody += email.emailDraft;
            emailSubject = email.emailSubject;

            messageBody += footer;

            if (!String.IsNullOrEmpty(emailServer) && passed_send_checks == true)
            {
                SmtpClient emailClient = new SmtpClient(emailServer, portNum);
                emailClient.EnableSsl      = sslEnabled;
                emailClient.DeliveryMethod = SmtpDeliveryMethod.Network;

                emailClient.Credentials = new System.Net.NetworkCredential(emailUsername, emailPassword);

                Regex emailCheck = new Regex("^.*<?[-a-zA-Z0-9!#$%&'*+/=?^_`{|}~]+(\\.[-a-zA-Z0-9!#$%&'*+/=?^_`{|}~]+)*@(([a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9]+)?){1,63}\\.)+([a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9]+)?){2,63}>?$");

                // create temp bulk email log -- used for tracking (must be created before sent so can include id in message html)
                int t_log_id = 0;
                qCom_TempBulkEmailLog t_log = new qCom_TempBulkEmailLog();
                t_log.EmailItemID  = emailID;
                t_log.EmailAddress = strFullEmail;
                t_log.Timestamp    = DateTime.Now;
                t_log.Insert();
                t_log_id = t_log.TempBulkEmailLogID;

                if (emailCheck.IsMatch(address.ToLower()))
                {
                    string finalBody = parseContentField(new string[] { Convert.ToString(user.UserID), userName, user.FirstName, user.LastName, user.Email, DateTime.Now.ToString(), value1, value2, value3, value4, strDID, Convert.ToString(emailID), Convert.ToString(t_log_id) }, messageBody);

                    string finalSubject = parseContentField(new string[] { Convert.ToString(user.UserID), userName, user.FirstName, user.LastName, user.Email, DateTime.Now.ToString(), value1, value2, value3, value4, strDID, Convert.ToString(emailID), Convert.ToString(t_log_id) }, emailSubject);

                    MailMessage mailout = new MailMessage(strFullEmail, address, finalSubject, finalBody);
                    mailout.IsBodyHtml = true;

                    emailClient.Send(mailout);

                    return_email_log_id = AddTransmissionLog(scopeID, address, userID, "single", finalSubject, emailID, full_email.CampaignID, strFromEmail);
                }
            }

            return(return_email_log_id);
        }
        public int SendDatabaseMailWithAttachment(string address, int emailID, int userID, string value1, string value2, string value3, string attachment)
        {
            int    return_email_log_id = 0;
            string header        = string.Empty;
            string footer        = string.Empty;
            string strFromEmail  = string.Empty;
            string fromName      = string.Empty;
            string emailUsername = null;
            string emailPassword = null;
            string emailServer   = null;
            bool   sslEnabled    = false;
            int    portNum       = 0;

            qPtl_User user = new qPtl_User((int)userID);

            // get email preferences
            var email_pref = qCom_EmailPreference.GetEmailPreferences();

            if (email_pref != null)
            {
                if (email_pref.EmailPreferencesID > 0)
                {
                    header        = email_pref.Header;
                    footer        = email_pref.Footer;
                    strFromEmail  = email_pref.FromEmailAddress;
                    fromName      = email_pref.FromName;
                    emailServer   = email_pref.SMTPServer;
                    emailUsername = email_pref.SMTPUsername;
                    emailPassword = email_pref.SMTPPassword;
                    sslEnabled    = email_pref.SMTPSSL;
                    portNum       = email_pref.SMTPPort;
                }
            }

            // format as friendly send address
            string strFullEmail = fromName + " <" + strFromEmail + ">";

            // get email info
            qCom_EmailTool email = new qCom_EmailTool(emailID);

            string messageBody = header;

            messageBody += email.emailDraft;
            messageBody += footer;

            if (email_pref.EmailPreferencesID > 0)
            {
                SmtpClient emailClient = new SmtpClient(emailServer, portNum);
                emailClient.EnableSsl      = sslEnabled;
                emailClient.DeliveryMethod = SmtpDeliveryMethod.Network;

                emailClient.Credentials = new System.Net.NetworkCredential(emailUsername, emailPassword);

                emailSubject = email.emailSubject;

                Regex emailCheck = new Regex("^.*<?[-a-z0-9!#$%&'*+/=?^_`{|}~]+(\\.[-a-z0-9!#$%&'*+/=?^_`{|}~]+)*@(([a-z]([-a-z0-9]*[a-z0-9]+)?){1,63}\\.)+([a-z]([-a-z0-9]*[a-z0-9]+)?){2,63}>?$");

                if (emailCheck.IsMatch(address.ToLower()))
                {
                    string finalBody    = string.Empty;
                    string finalSubject = string.Empty;
                    if (userID == 0)
                    {
                        finalBody    = parseContentField(new string[] { "", "", "", "", "", DateTime.Now.ToString(), value1, value2, value3 }, messageBody);
                        finalSubject = parseContentField(new string[] { "", "", "", "", "", DateTime.Now.ToString(), value1, value2, value3 }, emailSubject);
                    }
                    else
                    {
                        finalBody    = parseContentField(new string[] { Convert.ToString(user.UserID), user.UserName, user.FirstName, user.LastName, user.Email, DateTime.Now.ToString(), value1, value2, value3 }, messageBody);
                        finalSubject = parseContentField(new string[] { Convert.ToString(user.UserID), user.UserName, user.FirstName, user.LastName, user.Email, DateTime.Now.ToString(), value1, value2, value3 }, emailSubject);
                    }

                    MailMessage mailout = new MailMessage(strFullEmail, address, finalSubject, finalBody);
                    if (!String.IsNullOrEmpty(attachment))
                    {
                        Attachment attach = new Attachment(attachment, "");
                        mailout.Attachments.Add(attach);
                    }
                    mailout.IsBodyHtml = true;

                    emailClient.Send(mailout);

                    return_email_log_id = AddTransmissionLog(scopeID, address, userID, "single", finalSubject, 0, 0, address);
                }
            }

            return(return_email_log_id);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            // get all send events
            string sqlCode = string.Empty;

            sqlCode = "SELECT * FROM qCom_SendEvents_View WHERE (Available = 'Yes' AND Running = 'Yes' AND Recurring = 'Yes' AND GetDate() > StartDate) OR (Available = 'Yes' AND Running = 'Yes' AND Recurring = 'No' AND (GetDate() Between StartDate AND StartDate+1)) ORDER BY Priority ASC";
            qDbs_SQLcode sql = new qDbs_SQLcode();
            SqlDataReader eReader = sql.GetDataReader(sqlCode);

            if (eReader.HasRows)
            {
                while (eReader.Read())
                {
                    // see if there are custom email preferences if this send event is associated with a campaign
                    int campaign_id = 0;
                    string custom_email = string.Empty;
                    string custom_email_from = string.Empty;
                    bool get_custom_did = false;

                    if (!String.IsNullOrEmpty(Convert.ToString(eReader["CampaignID"])))
                        campaign_id = Convert.ToInt32(eReader["CampaignID"]);

                    if (campaign_id > 0)
                    {
                        var pref = qCom_CampaignPreference.GetCampaignPreferences(campaign_id);
                        if (pref != null)
                        {
                            if (pref.CampaignPreferenceID > 0)
                            {
                                if (!String.IsNullOrEmpty(pref.CampaignEmail))
                                    custom_email = pref.CampaignEmail;
                                if (!String.IsNullOrEmpty(pref.CampaignEmailFrom))
                                    custom_email_from = pref.CampaignEmailFrom;

                                // see if we need to get / integrated a custom DID
                                if (pref.IncludeCustomDID == true)
                                    get_custom_did = true;
                            }
                        }
                    }

                    // get email preferences
                    string sqlCode2 = "SELECT TOP(1) * FROM qCom_EmailPreferences WHERE Available = 'Yes'";
                    SqlDataReader pReader = sql.GetDataReader(sqlCode2);

                    pReader.Read();
                    string header = Convert.ToString(pReader["Header"]);
                    string footer = Convert.ToString(pReader["Footer"]);
                    string unsubscribe = Convert.ToString(pReader["Unsubscribe"]);
                    string fromEmailAddress = string.Empty;
                    string fromName = string.Empty;
                    if (!String.IsNullOrEmpty(custom_email))
                        fromEmailAddress = custom_email;
                    else
                        fromEmailAddress = Convert.ToString(pReader["FromEmailAddress"]);
                    if (!String.IsNullOrEmpty(custom_email_from))
                        fromName = custom_email_from;
                    else
                        fromName = Convert.ToString(pReader["fromName"]);
                    pReader.Close();

                    //try
                    //{
                        lblMessage.Text += "<br>Sending...";
                        // create object
                        int emailID = Convert.ToInt32(eReader["emailID"]);
                        string contactQuery = "SELECT " + Convert.ToString(eReader["sqlSELECT"]) + " FROM " + Convert.ToString(eReader["sqlFROM"]) + " WHERE " + Convert.ToString(eReader["sqlWHERE"]);
                        bool is_contact_list = false;
                        if (Convert.ToString(eReader["sqlFROM"]).Contains("qCom_Contacts"))
                            is_contact_list = true;

                        qCom_EmailTool email = new qCom_EmailTool(emailID);

                        // get addresses
                        string[][] contacts = email.GetSendEventContacts(contactQuery, get_custom_did, campaign_id, Convert.ToInt32(Context.Items["ScopeID"]), is_contact_list);

                        string messageBody = string.Empty;
                        string includeHeader = Convert.ToString(eReader["IncludeHeader"]);
                        string includeFooter = Convert.ToString(eReader["IncludeFooter"]);
                        string includeUnsubscribe = Convert.ToString(eReader["IncludeUnsubscribe"]);

                        if (includeHeader == "Yes")
                        {
                            messageBody += header;
                        }

                        messageBody += email.emailDraft;

                        if (includeFooter == "Yes")
                        {
                            messageBody += footer;
                        }
                        if (includeUnsubscribe == "Yes")
                        {
                            messageBody += unsubscribe;
                        }

                        //(string[][] addresses, string strFrom, string strFromEmail, string requestURL, string strSubject, string rawEmailContent, string userID, string value1, string value2, bool sendCopyToAdmins, bool noDuplicatesToday, bool noDontSend, int emailID)
                        ArrayList[] output = email.SendMail(contacts, fromName, fromEmailAddress, "bulkemail", email.emailSubject, messageBody, "", "", "", "", "", false, true, true, emailID, get_custom_did, campaign_id);

                        lblMessage.Text += "finished sending email: " + email.emailSubject + "; send event id = " + Convert.ToString(eReader["SendEventID"]) + "; number of recipients=" + contacts.Length;
                    //}
                    //catch
                    //{
                    //    lblMessage.Text += "A problem has occurred<br>";
                    //}
                }

                eReader.Close();

            }
            else
            {
                lblMessage.Text += "There are no scheduled send events.<br>";
            }

        }
        else
        {
            lblMessage.Text += "Problem with key or page incorrectly loaded.<br>";
        }
    }
        public void SendNotification(int emailID, int UserID, int ProfileUserID, string comment, int ReferenceID)
        {
            qCom_EmailTool email = new qCom_EmailTool();

            qPtl_User user = new qPtl_User(ProfileUserID);
            qPtl_User commentingUser = new qPtl_User(UserID);

            if (!string.IsNullOrEmpty(user.Email))
                email.SendDatabaseMail(user.Email, emailID, user.UserID, commentingUser.UserName, comment, ReferenceID.ToString(), string.Empty, string.Empty, false);
        }
        public int SendDatabaseMailWithAttachment(string address, int emailID, int userID, string value1, string value2, string value3, string attachment)
        {
            int return_email_log_id = 0;
            string header = string.Empty;
            string footer = string.Empty;
            string strFromEmail = string.Empty;
            string fromName = string.Empty;
            string emailUsername = null;
            string emailPassword = null;
            string emailServer = null;
            bool sslEnabled = false;
            int portNum = 0;

            qPtl_User user = new qPtl_User((int)userID);

            // get email preferences
            var email_pref = qCom_EmailPreference.GetEmailPreferences();

            if (email_pref != null)
            {
                if (email_pref.EmailPreferencesID > 0)
                {
                    header = email_pref.Header;
                    footer = email_pref.Footer;
                    strFromEmail = email_pref.FromEmailAddress;
                    fromName = email_pref.FromName;
                    emailServer = email_pref.SMTPServer;
                    emailUsername = email_pref.SMTPUsername;
                    emailPassword = email_pref.SMTPPassword;
                    sslEnabled = email_pref.SMTPSSL;
                    portNum = email_pref.SMTPPort;
                }
            }

            // format as friendly send address
            string strFullEmail = fromName + " <" + strFromEmail + ">";

            // get email info
            qCom_EmailTool email = new qCom_EmailTool(emailID);

            string messageBody = header;
            messageBody += email.emailDraft;
            messageBody += footer;

            if (email_pref.EmailPreferencesID > 0)
            {
                SmtpClient emailClient = new SmtpClient(emailServer, portNum);
                emailClient.EnableSsl = sslEnabled;
                emailClient.DeliveryMethod = SmtpDeliveryMethod.Network;

                emailClient.Credentials = new System.Net.NetworkCredential(emailUsername, emailPassword);

                emailSubject = email.emailSubject;

                Regex emailCheck = new Regex("^.*<?[-a-z0-9!#$%&'*+/=?^_`{|}~]+(\\.[-a-z0-9!#$%&'*+/=?^_`{|}~]+)*@(([a-z]([-a-z0-9]*[a-z0-9]+)?){1,63}\\.)+([a-z]([-a-z0-9]*[a-z0-9]+)?){2,63}>?$");

                if (emailCheck.IsMatch(address.ToLower()))
                {
                    string finalBody = string.Empty;
                    string finalSubject = string.Empty;
                    if (userID == 0)
                    {
                        finalBody = parseContentField(new string[] { "", "", "", "", "", DateTime.Now.ToString(), value1, value2, value3 }, messageBody);
                        finalSubject = parseContentField(new string[] { "", "", "", "", "", DateTime.Now.ToString(), value1, value2, value3 }, emailSubject);
                    }
                    else
                    {
                        finalBody = parseContentField(new string[] { Convert.ToString(user.UserID), user.UserName, user.FirstName, user.LastName, user.Email, DateTime.Now.ToString(), value1, value2, value3 }, messageBody);
                        finalSubject = parseContentField(new string[] { Convert.ToString(user.UserID), user.UserName, user.FirstName, user.LastName, user.Email, DateTime.Now.ToString(), value1, value2, value3 }, emailSubject);
                    }

                    MailMessage mailout = new MailMessage(strFullEmail, address, finalSubject, finalBody);
                    if (!String.IsNullOrEmpty(attachment))
                    {
                        Attachment attach = new Attachment(attachment, "");
                        mailout.Attachments.Add(attach);
                    }
                    mailout.IsBodyHtml = true;

                    emailClient.Send(mailout);

                    return_email_log_id = AddTransmissionLog(scopeID, address, userID, "single", finalSubject, 0, 0, address);
                }
            }

            return return_email_log_id;
        }
        //Send to just one address with text replacement
        public int SendDatabaseMail(string address, int emailID, int userID, string userName, string value1, string value2, string value3, string value4, bool no_duplicates_today)
        {
            // get email info
            qCom_EmailTool email = new qCom_EmailTool(emailID);
            qCom_EmailItem full_email = new qCom_EmailItem(emailID);

            string header = string.Empty;
            string footer = string.Empty;
            string strFromEmail = string.Empty;
            string fromName = string.Empty;
            string emailUsername = null;
            string emailPassword = null;
            string emailServer = null;
            bool sslEnabled = false;
            int portNum = 0;
            string strDID = string.Empty;
            int return_email_log_id = 0;
            bool passed_send_checks = false;
            bool already_sent_today = true;
            string returnedEmail = string.Empty;
            bool ok_to_send = false;
            string noEmail = string.Empty;

            // Check to see if email already sent to user today
            if (no_duplicates_today == true)
            {
                var prior_current_day_log = qCom_EmailLog.CheckForEmailSentLastDay(address);

                if (prior_current_day_log == null)
                {
                    already_sent_today = false;
                }
            }
            else
            {
                already_sent_today = false;
            }

            qCom_UserPreference_View u_pref = new qCom_UserPreference_View(address);
            if (u_pref.UserID > 0)
            {
                if (u_pref.OkBulkEmail == "Yes" || u_pref.OkEmail == "Yes")
                {
                    ok_to_send = true;
                }
            }
            else
                ok_to_send = true;

            if (already_sent_today == false && ok_to_send == true)
                passed_send_checks = true;
            else
                passed_send_checks = false;

            qPtl_User user = new qPtl_User(Convert.ToInt32(userID));
            if (user.UserID == 0)
            {
                user.Email = "";
                user.FirstName = "";
                user.LastName = "";
            }

            // load default email preferences
            if (String.IsNullOrEmpty(emailServer))
            {
                var email_pref = qCom_EmailPreference.GetEmailPreferences();

                if (email_pref != null)
                {
                    if (email_pref.EmailPreferencesID > 0)
                    {
                        header = email_pref.Header;
                        footer = email_pref.Footer;
                        strFromEmail = email_pref.FromEmailAddress;
                        fromName = email_pref.FromName;
                        emailServer = email_pref.SMTPServer;
                        emailUsername = email_pref.SMTPUsername;
                        emailPassword = email_pref.SMTPPassword;
                        sslEnabled = email_pref.SMTPSSL;
                        portNum = email_pref.SMTPPort;
                    }
                }
            }

            // format as friendly send address
            string strFullEmail = string.Empty;
            if (!String.IsNullOrEmpty(fromName))
                strFullEmail = fromName + " <" + strFromEmail + ">";
            else
                strFullEmail = strFromEmail;

            string messageBody = header;

            messageBody += email.emailDraft;
            emailSubject = email.emailSubject;

            messageBody += footer;

            if (!String.IsNullOrEmpty(emailServer) && passed_send_checks == true)
            {
                SmtpClient emailClient = new SmtpClient(emailServer, portNum);
                emailClient.EnableSsl = sslEnabled;
                emailClient.DeliveryMethod = SmtpDeliveryMethod.Network;

                emailClient.Credentials = new System.Net.NetworkCredential(emailUsername, emailPassword);

                Regex emailCheck = new Regex("^.*<?[-a-zA-Z0-9!#$%&'*+/=?^_`{|}~]+(\\.[-a-zA-Z0-9!#$%&'*+/=?^_`{|}~]+)*@(([a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9]+)?){1,63}\\.)+([a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9]+)?){2,63}>?$");

                // create temp bulk email log -- used for tracking (must be created before sent so can include id in message html)
                int t_log_id = 0;
                qCom_TempBulkEmailLog t_log = new qCom_TempBulkEmailLog();
                t_log.EmailItemID = emailID;
                t_log.EmailAddress = strFullEmail;
                t_log.Timestamp = DateTime.Now;
                t_log.Insert();
                t_log_id = t_log.TempBulkEmailLogID;

                if (emailCheck.IsMatch(address.ToLower()))
                {
                    string finalBody = parseContentField(new string[] { Convert.ToString(user.UserID), userName, user.FirstName, user.LastName, user.Email, DateTime.Now.ToString(), value1, value2, value3, value4, strDID, Convert.ToString(emailID), Convert.ToString(t_log_id) }, messageBody);

                    string finalSubject = parseContentField(new string[] { Convert.ToString(user.UserID), userName, user.FirstName, user.LastName, user.Email, DateTime.Now.ToString(), value1, value2, value3, value4, strDID, Convert.ToString(emailID), Convert.ToString(t_log_id) }, emailSubject);

                    MailMessage mailout = new MailMessage(strFullEmail, address, finalSubject, finalBody);
                    mailout.IsBodyHtml = true;

                    emailClient.Send(mailout);

                    return_email_log_id = AddTransmissionLog(scopeID, address, userID, "single", finalSubject, emailID, full_email.CampaignID, strFromEmail);
                }
            }

            return return_email_log_id;
        }
    protected void btnSendWelcomeEmail_Click(object sender, EventArgs e)
    {
        string strMessage = string.Empty;
        lblWelcomeEmailMessage.Text = string.Empty;

        int userID = Convert.ToInt32(Request.QueryString["userID"]);
        qPtl_User user = new qPtl_User(userID);

        if (user.UserID > 0)
        {
            if (!String.IsNullOrEmpty(user.Email))
            {
                if (user.SetPasswordResetCode(user.UserID))
                {
                    qPtl_User user2 = new qPtl_User(userID);
                    int welcomeEmailID = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Email_WelcomeEmailID"]);
                    string publicURL = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["CMS_URL"]);
                    string siteName = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["Site_ShortName"]);
                    qCom_EmailTool etool = new qCom_EmailTool(welcomeEmailID, user.UserID);
                    Regex regParseable = new Regex("{FirstName}");
                    string emailContent = regParseable.Replace(etool.emailDraft, user.FirstName);
                    regParseable = new Regex("{UserID}");
                    emailContent = regParseable.Replace(emailContent, user.UserID.ToString());
                    regParseable = new Regex("{ResetCode}");
                    emailContent = regParseable.Replace(emailContent, user2.PasswordResetCode);
                    regParseable = new Regex("{SiteURL}");
                    emailContent = regParseable.Replace(emailContent, Request.Url.Authority + HttpRuntime.AppDomainAppVirtualPath);
                    int email_log_id = 0;
                    email_log_id = etool.SendDatabaseMail(user.Email, welcomeEmailID, user.UserID, user.UserName, user2.PasswordResetCode, Request.Url.Authority + HttpRuntime.AppDomainAppVirtualPath.TrimEnd('/'), string.Empty, string.Empty, false);
                    if (email_log_id > 0)
                        lblWelcomeEmailMessage.Text += "&nbsp;&nbsp;<i class=\"icon-check\"></i> Sent welcome message to: " + user.Email + " at " + DateTime.Now + "<br>";
                    else
                        lblWelcomeEmailMessage.Text += "&nbsp;&nbsp;<i class=\"icon-warning-sign\"></i> An error occured sending message for: " + user.Email + "<br>";
                }
            }
            else
            {
                lblWelcomeEmailMessage.Text += "** This user does not have an email on record -- welcome email cannot be sent ***<br><br>";
            }
        }

        lblWelcomeEmailMessage.Visible = true;
        //btnSendInvitation.Enabled = false;
    }
    protected void btnSendWaitlistEmail_Click(object sender, EventArgs e)
    {
        int user_id = Convert.ToInt32(Request.QueryString["userID"]);
        int training_id = Convert.ToInt32(Request.QueryString["trainingID"]);

        qPtl_User user = new qPtl_User(user_id);
        qLrn_Training training = new qLrn_Training(training_id);

        if (user.UserID > 0)
        {
            if (!String.IsNullOrEmpty(user.Email))
            {
                int email_id = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["email_RemovedWaitlistID"]);

                qCom_EmailTool email = new qCom_EmailTool(email_id);

                int sent_email_log_id = email.SendDatabaseMail(user.Email, email_id, user.UserID, user.FirstName, training.Title, Convert.ToString(training.TrainingID), "", "", false);

                if (sent_email_log_id > 0)
                {
                    lblMessage.Text = "* Email Successfully Sent";
                    btnSendWaitlistEmail.Visible = false;
                }
                else
                    lblMessage.Text += "** An error occured sending message for: " + user.Email + "<br><br>";
            }
            else
            {
                lblMessage.Text += "** This user does not have an email on record -- welcome email cannot be sent ***<br><br>";
            }
        }
    }
        public void Insert()
        {
            NotificationID = Convert.ToInt32(container.Insert());

            //if email notification enabled, send an email
            string send_notification_email = System.Configuration.ConfigurationManager.AppSettings["Email_SendNotificationEmail"];
            if (!String.IsNullOrEmpty(send_notification_email))
            {
                if (send_notification_email == "true")
                {
                    qPtl_Notification notification = new qPtl_Notification(NotificationID);
                    qPtl_User owner = new qPtl_User(notification.OwnerID);
                    qPtl_User actor = new qPtl_User(notification.ActorID);
                    int notification_email_id = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Email_NotificationEmailID"]);
                    if (!String.IsNullOrEmpty(Convert.ToString(notification_email_id)))
                    {
                        if (notification_email_id > 0)
                        {
                            try
                            {
                                qCom_EmailTool email = new qCom_EmailTool(notification_email_id);
                                email.SendDatabaseMail(owner.Email, notification_email_id, owner.UserID, notification.Text, actor.UserName, "", "", "", false);
                            }
                            catch
                            {
                                // do nothing
                            }
                        }
                    }
                }
            }
        }
        protected void SendTaskEmail(int task_type_id, int created_by, int reference_id, string description)
        {
            string request_task_emails = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["TaskEmailList"]);
            qCom_EmailPreference preferences = new qCom_EmailPreference();
            string system_from = preferences.FromName;
            string system_email_address = preferences.FromEmailAddress;
            int curr_email_id = 0;

            qPtl_User curr_user = new qPtl_User(created_by);

            if (!String.IsNullOrEmpty(request_task_emails))
            {
                switch (task_type_id)
                {
                    case 1:     // review blog
                        curr_email_id = Convert.ToInt32(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["report_blog_EmailID"]));
                        break;
                    case 2:     // approve image
                        curr_email_id = Convert.ToInt32(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["report_newpic_EmailID"]));
                        break;
                    case 3:     // approve video
                        curr_email_id = Convert.ToInt32(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["report_video_EmailID"]));
                        break;
                    case 4:     // review site report
                        curr_email_id = Convert.ToInt32(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["report_issue_EmailID"]));
                        break;
                    case 5:     // review reported message
                        curr_email_id = Convert.ToInt32(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["report_message_EmailID"]));
                        break;
                    case 6:     // review banned word
                        curr_email_id = Convert.ToInt32(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["report_banned_word_EmailID"]));
                        break;
                }

                qCom_EmailItem email = new qCom_EmailItem(curr_email_id);

                ArrayList addresses = new ArrayList();
                q_Helper helper = new q_Helper();
                addresses = helper.optionsToArrayList(request_task_emails);

                qCom_EmailTool email_send = new qCom_EmailTool();
                int sent_email_log_id = 0;

                foreach (string address in addresses)
                {
                    try
                    {
                        sent_email_log_id = email_send.SendDatabaseMail(address, curr_email_id, created_by, curr_user.UserName, Convert.ToString(reference_id), description, "", "", false);
                    }
                    catch
                    {
                        // email failure
                    }
                }
            }
        }