private bool PrepareEmail(SendTokenizedBulkEmail email, ref string message, ref ModuleMessage.ModuleMessageType messageType)
        {
            bool isValid = true;

            switch (teMessage.Mode)
            {
                case "RICH":
                    email.BodyFormat = MailFormat.Html;
                    break;
                default:
                    email.BodyFormat = MailFormat.Text;
                    break;
            }

            switch (cboPriority.SelectedItem.Value)
            {
                case "1":
                    email.Priority = MailPriority.High;
                    break;
                case "2":
                    email.Priority = MailPriority.Normal;
                    break;
                case "3":
                    email.Priority = MailPriority.Low;
                    break;
                default:
                    isValid = false;
                    break;
            }

            if (txtFrom.Text != string.Empty && email.SendingUser.Email != txtFrom.Text)
            {
                var myUser = email.SendingUser ?? new UserInfo();
                myUser.Email = txtFrom.Text;
                email.SendingUser = myUser;
            }

            if (txtReplyTo.Text != string.Empty && email.ReplyTo.Email != txtReplyTo.Text)
            {
                var myUser = new UserInfo { Email = txtReplyTo.Text };
                email.ReplyTo = myUser;
            }

            if (selLanguage.Visible && selLanguage.SelectedLanguages != null)
            {
                email.LanguageFilter = selLanguage.SelectedLanguages;
            }

            if (ctlAttachment.Url.StartsWith("FileID="))
            {
                int fileId = int.Parse(ctlAttachment.Url.Substring(7));
                var objFileInfo = FileManager.Instance.GetFile(fileId);
                //TODO: support secure storage locations for attachments! [sleupold 06/15/2007]
                email.AddAttachment(FileManager.Instance.GetFileContent(objFileInfo),
                                               new ContentType { MediaType = objFileInfo.ContentType, Name = objFileInfo.FileName });
            }

            switch (cboSendMethod.SelectedItem.Value)
            {
                case "TO":
                    email.AddressMethod = SendTokenizedBulkEmail.AddressMethods.Send_TO;
                    break;
                case "BCC":
                    email.AddressMethod = SendTokenizedBulkEmail.AddressMethods.Send_BCC;
                    break;
                case "RELAY":
                    email.AddressMethod = SendTokenizedBulkEmail.AddressMethods.Send_Relay;
                    if (string.IsNullOrEmpty(txtRelayAddress.Text))
                    {
                        message = string.Format(Localization.GetString("MessagesSentCount", LocalResourceFile), -1);
                        messageType = ModuleMessage.ModuleMessageType.YellowWarning;
                        isValid = false;
                    }
                    else
                    {
                        email.RelayEmailAddress = txtRelayAddress.Text;
                    }
                    break;
            }

            email.SuppressTokenReplace = !chkReplaceTokens.Checked;

            return isValid;
        }
        private void SendMailSynchronously(SendTokenizedBulkEmail email, out string strResult, out ModuleMessage.ModuleMessageType msgResult)
        {
            int mailsSent = email.SendMails();

            if (mailsSent > 0)
            {
                strResult = string.Format(Localization.GetString("MessagesSentCount", LocalResourceFile), mailsSent);
                msgResult = ModuleMessage.ModuleMessageType.GreenSuccess;
            }
            else
            {
                strResult = string.Format(Localization.GetString("NoMessagesSent", LocalResourceFile), email.SendingUser.Email);
                msgResult = ModuleMessage.ModuleMessageType.YellowWarning;
            }
        }
 private void SendAndDispose(SendTokenizedBulkEmail email)
 {
     using (email)
     {
         email.Send();
     }
 }
        private void SendMailAsyncronously(SendTokenizedBulkEmail email, out string message, out ModuleMessage.ModuleMessageType messageType)
        {
            //First send off a test message
            var strStartSubj = Localization.GetString("EMAIL_BulkMailStart_Subject.Text", Localization.GlobalResourceFile);
            if (!string.IsNullOrEmpty(strStartSubj)) strStartSubj = string.Format(strStartSubj, txtSubject.Text);

            var strStartBody = Localization.GetString("EMAIL_BulkMailStart_Body.Text", Localization.GlobalResourceFile);
            if (!string.IsNullOrEmpty(strStartBody)) strStartBody = string.Format(strStartBody, txtSubject.Text, UserInfo.DisplayName, email.Recipients().Count);

            var sendMailResult = Mail.SendMail(txtFrom.Text,
                txtFrom.Text,
                "",
                "",
                MailPriority.Normal,
                strStartSubj,
                MailFormat.Text,
                Encoding.UTF8,
                strStartBody,
                "",
                Host.SMTPServer,
                Host.SMTPAuthentication,
                Host.SMTPUsername,
                Host.SMTPPassword,
                Host.EnableSMTPSSL);

            if (string.IsNullOrEmpty(sendMailResult))
            {
                var objThread = new Thread(() => SendAndDispose(email));
                objThread.Start();
                message = Localization.GetString("MessageSent", LocalResourceFile);
                messageType = ModuleMessage.ModuleMessageType.GreenSuccess;
            }
            else
            {
                message = string.Format(Localization.GetString("NoMessagesSentPlusError", LocalResourceFile), sendMailResult);
                messageType = ModuleMessage.ModuleMessageType.YellowWarning;
            }
        }
        private void SendEmail(List<string> roleNames, List<UserInfo> users, ref string message, ref ModuleMessage.ModuleMessageType messageType)
        {
            //it is awkward to ensure that email is disposed correctly because when sent asynch it should be disposed by the  asynch thread
            var email = new SendTokenizedBulkEmail(roleNames, users, /*removeDuplicates*/ true, txtSubject.Text, ConvertToAbsoluteUrls(teMessage.Text));

            bool isValid;
            try
            {
                isValid = PrepareEmail(email, ref message, ref messageType);
            }
            catch (Exception)
            {
                email.Dispose();
                throw;
            }

            if (isValid)
            {

                if (optSendAction.SelectedItem.Value == "S")
                {
                    try
                    {
                        SendMailSynchronously(email, out message, out messageType);
                    }
                    finally
                    {
                        email.Dispose();
                    }
                }
                else
                {
                    SendMailAsyncronously(email, out message, out messageType);
                    //dispose will be handled by async thread
                }
            }
        }
        protected void DebateList_InsertCommand(object sender, TreeListCommandEventArgs e)
        {
            string ConnString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
            string commandText = @"INSERT INTO uDebate_Forum_Posts (ThreadID, ParentID, UserID, PostLevel, SortOrder, Subject,
                                   Message, PostDate, IsPublished, PostType, Active, Published_Date, Complaint_Count, ModuleID)
                                   VALUES (@ThreadID, @ParentID, " + UserInfo.UserID + @", 1, 1, @Subject, @Message, getDate(), 1,
                                           @PostType,1,getDate(),0," + ModuleId + ")";

            SqlConnection conn = new SqlConnection(ConnString);
            SqlCommand command = new SqlCommand(commandText, conn);
            Hashtable table = new Hashtable();
            TreeListEditFormInsertItem item = e.Item as TreeListEditFormInsertItem;
            table["Subject"] = (item.FindControl("txtSubjectPost") as TextBox).Text;
            table["Message"] = (item.FindControl("txtReply") as DotNetNuke.Web.UI.WebControls.DnnEditor).GetHtml(EditorStripHtmlOptions.None).Replace("'", "\"");

            RadioButton Issue = (item.FindControl("IssueRadio") as RadioButton);
            RadioButton Alter = (item.FindControl("AlterRadio") as RadioButton);
            RadioButton Pro = (item.FindControl("ProRadio") as RadioButton);
            RadioButton Con = (item.FindControl("ConRadio") as RadioButton);
            RadioButton Comment = (item.FindControl("CommentRadio") as RadioButton);

            String selection = String.Empty;

            if (Issue.Checked)
            {
                selection = "1";
            }
            else if (Alter.Checked)
            {
                selection = "2";
            }
            else if (Pro.Checked)
            {
                selection = "3";
            }
            else if (Con.Checked)
            {
                selection = "4";
            }
            else if (Comment.Checked)
            {
                selection = "8";
            }

            table["PostType"] = selection;
            command.Parameters.AddWithValue("ThreadID", Thread_ID);
            command.Parameters.AddWithValue("Subject", table["Subject"]);
            command.Parameters.AddWithValue("Message", table["Message"]);
            command.Parameters.AddWithValue("PostType", table["PostType"]);

            object parentValue;
            if (item.ParentItem != null)
            {
                parentValue = item.ParentItem.GetDataKeyValue("ID");
            }
            else
            {
                parentValue = "0";
            }

            command.Parameters.AddWithValue("ParentID", parentValue);

            conn.Open();
            try
            {
                command.ExecuteNonQuery();
                /*if the new post is a reply we have to disable edit mode of parent and expand it */
                if (item.ParentItem != null)
                {
                    item.ParentItem.Expanded = true;
                    item.ParentItem.IsChildInserted = false;
                }
                DebateList.IsItemInserted = false;

                DebateList.Rebind();
                DataRow lastPost = getLatestPostOfThread(Thread_ID);
                if (lastPost != null)
                    FindAndSelectItem(Convert.ToInt32(lastPost["ID"]));

            }
            finally
            {
                conn.Close();
            }

            /* If a user posts to a thread we add him to the notification list*/
            AddUserToNotified(Thread_ID);
            notifyCheck.Checked = true;

            string fromAddress = "*****@*****.**";
            string subject = "OGP Ireland - New Post";
            string body = "Hi, <br /><br/>A new post has been submitted to the OGP Ireland thread \"<b>" +
                         getDescription(Thread_ID) + "\"</b>.<br /> To see this post, visit " +
                        ConfigurationManager.AppSettings["DomainName"] +/* "/" +
                        System.Threading.Thread.CurrentThread.CurrentCulture.Name +*/
                        "/udebatediscussion.aspx?Thread=" + Thread_ID + "<br /><br/>Kind Regards,<br /><br/>"+
                        PortalSettings.PortalName + "<br /><a href='" + PortalSettings.DefaultPortalAlias +
                        "'>" + PortalSettings.DefaultPortalAlias + "</a>" + "<br /><br />" +
                        "<img src='http://" + PortalSettings.DefaultPortalAlias + "/Portals/0/pbp_logo270.jpg'/>";

            SendTokenizedBulkEmail mailer = new SendTokenizedBulkEmail();

            /* Notify moderators of the new post*/
            switch (getPostLanguageByThread(Thread_ID).ToLower())
            {
                case "el-gr":
                     Entities.Users.UserInfo user = new Entities.Users.UserInfo();
                     user.Email = "*****@*****.**";
                     mailer.AddAddressedUser(user);

                    break;
               /* case "es-es":
                    Entities.Users.UserInfo user3 = new Entities.Users.UserInfo();
                    user3.Email = "*****@*****.**";
                     mailer.AddAddressedUser(user3);
                     Entities.Users.UserInfo user4 = new Entities.Users.UserInfo();
                    user4.Email = "*****@*****.**";
                     mailer.AddAddressedUser(user4);
                     Entities.Users.UserInfo user5 = new Entities.Users.UserInfo();
                     user5.Email = "*****@*****.**";
                     mailer.AddAddressedUser(user5);
                    break;
                case "it-it":
                    Entities.Users.UserInfo user7 = new Entities.Users.UserInfo();
                    user7.Email = "*****@*****.**";
                     mailer.AddAddressedUser(user7);
                    break;
                case "hu-hu":
                    Entities.Users.UserInfo user9 = new Entities.Users.UserInfo();
                    user9.Email = "*****@*****.**";
                     mailer.AddAddressedUser(user9);
                    break;
                case "en-gb":
                    Entities.Users.UserInfo user11 = new Entities.Users.UserInfo();
                    user11.Email = "*****@*****.**";
                     mailer.AddAddressedUser(user11);
                     Entities.Users.UserInfo user12 = new Entities.Users.UserInfo();
                     user12.Email = "*****@*****.**";
                     mailer.AddAddressedUser(user12);
                    break;*/
                default:   break;
            }

            Entities.Users.UserInfo user14 = new Entities.Users.UserInfo();
            user14.Email = "*****@*****.**";
            mailer.AddAddressedUser(user14);

            mailer.Priority = DotNetNuke.Services.Mail.MailPriority.Normal;

            mailer.AddressMethod = DotNetNuke.Services.Mail.SendTokenizedBulkEmail.AddressMethods.Send_TO;

            Entities.Users.UserInfo senderUser = new Entities.Users.UserInfo();
            senderUser.Email = "*****@*****.**";

            mailer.SendingUser = senderUser;

            mailer.ReportRecipients = false;

            mailer.Subject = subject;

            mailer.Body = body;

            mailer.BodyFormat = DotNetNuke.Services.Mail.MailFormat.Html;

            Thread objThread = new Thread(mailer.Send);

            objThread.Start();

            /* Send an email to all the subscribed users of this thread*/
            string subjectNotify = "OGP Ireland - There is a new post in the thread you are following";
            string bodyNotify = "Hi, <br /><br/>A new post has been submitted to the OGP Ireland thread \"<b>" +
                         getDescription(Thread_ID) + "\"</b>.<br /> To see this post, visit " +
                        ConfigurationManager.AppSettings["DomainName"] + /*"/" +
                        System.Threading.Thread.CurrentThread.CurrentCulture.Name +*/
                        "/udebatediscussion.aspx?Thread=" + Thread_ID + "<br /><br/>Kind Regards,<br /><br/>"+
                        PortalSettings.PortalName + "<br /><a href='" + PortalSettings.DefaultPortalAlias +
                        "'>" + PortalSettings.DefaultPortalAlias + "</a>" + "<br /><br />" +
                        "<img src='http://" + PortalSettings.DefaultPortalAlias + "/Portals/0/pbp_logo270.jpg'/>";

            string SQL_notified = "SELECT userID,userEmail FROM uDebate_Forum_Notifications where threadID=" + Thread_ID;
            try
            {
                DataSet ds = ATC.Database.sqlExecuteDataSet(SQL_notified);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    SendTokenizedBulkEmail notificationMailer = new SendTokenizedBulkEmail();

                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        // Only send email to users different than the current one (the post writer)
                        if (UserId != Int32.Parse(row["userID"].ToString()))
                        {
                            int numRecs = 100;
                            ArrayList findEmailinRegistered = Entities.Users.UserController.GetUsersByEmail(PortalId, row["userEmail"].ToString(), 0, 10, ref numRecs,false,false);

                            //Check that the user is still registered
                            if (findEmailinRegistered.Count > 0)
                            {
                                Entities.Users.UserInfo newUser = new Entities.Users.UserInfo();
                                newUser.Email = row["userEmail"].ToString();
                                notificationMailer.AddAddressedUser(newUser);
                            }
                            //if no, remove him from the list of notified users
                            else
                            {
                                RemoveUserFromNotified(row["userEmail"].ToString());

                            }
                        }
                    }

                    notificationMailer.Priority = DotNetNuke.Services.Mail.MailPriority.Normal;

                    notificationMailer.AddressMethod = DotNetNuke.Services.Mail.SendTokenizedBulkEmail.AddressMethods.Send_TO;

                    Entities.Users.UserInfo sendingUser = new Entities.Users.UserInfo();
                    sendingUser.Email = "*****@*****.**";

                    notificationMailer.SendingUser = sendingUser;

                    notificationMailer.ReportRecipients = true;

                    notificationMailer.Subject = subjectNotify;

                    notificationMailer.Body = bodyNotify;

                    notificationMailer.BodyFormat = DotNetNuke.Services.Mail.MailFormat.Html;

                    Thread objThread1 = new Thread(notificationMailer.Send);

                    objThread1.Start();
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }