如何根据每个帐户的最大中继策略发送邮件

How to send mails ar per max relays policy of each account

我刚刚开发了一个 BulkMail Web 应用程序。我有一个名为 mail1.aspx 的 Web 表单。现在我只想发送每个用户创建时提供的最大中继邮件。我有数据库字段名称 MaxCount,它限制从每个用户发送邮件。现在我只想检查之前的 SentDateTime 列,当前 DateTime 出现在 Count <= MaxCount 字段中。这是以前订阅者计数的计数器。在这里,我包括了我的 linqtosql table 详细信息。

这是我的发送按钮代码:

     protected void btn_save_Click(object sender, EventArgs e)
        {
            List<string> file_names = new List<string>();
            string ToUser = txt_ComName3.Text.Trim();
            char touser1 = Convert.ToChar(ToUser.Substring(ToUser.Length - 1, 1));
            string Cc = null;
            if (!string.IsNullOrEmpty(txt_ComName4.Text.Trim()))
            {
                Cc = txt_ComName4.Text.Trim();
            }
            string Bcc = null;
            if (!string.IsNullOrEmpty(txt_ComName5.Text.Trim()))
            {
                Bcc = txt_ComName5.Text.Trim();
            }
            char? cc1 = null;
            if (!string.IsNullOrEmpty(Cc))
            {
                cc1 = Convert.ToChar(Cc.Substring(Cc.Length - 1, 1));
            }
            char? bcc1 = null;
            if (!string.IsNullOrEmpty(Bcc))
            {
                bcc1 = Convert.ToChar(Bcc.Substring(Bcc.Length - 1, 1));
            }
            bool FileAttached;
            if (FileUpload1.HasFile)
            {
                FileAttached = true;
            }
            else
            {
                FileAttached = false;
            }
            int templateId = 0;
            if (!string.IsNullOrEmpty(template_id.Value.Trim()))
            {
                templateId = Convert.ToInt32(template_id.Value.ToString());
            }
            else
            {
                templateId = 0;
            }
            using (DataClassesDataContext db = new DataClassesDataContext())
            {
                string Email = db.FromUsers.Where(f => f.EmailAddress.Equals(txt_ComName2.Text.Trim()) && f.user_id.Equals(int.Parse(CommonLogic.GetSessionValue("user_id").ToString()))).Select(f => f.EmailAddress).FirstOrDefault();
                string Host = db.FromUsers.Where(f => f.EmailAddress.Equals(txt_ComName2.Text.Trim()) && f.user_id.Equals(int.Parse(CommonLogic.GetSessionValue("user_id").ToString()))).Select(f => f.Host).FirstOrDefault();
                string Port = db.FromUsers.Where(f => f.EmailAddress.Equals(txt_ComName2.Text.Trim()) && f.user_id.Equals(int.Parse(CommonLogic.GetSessionValue("user_id").ToString()))).Select(f => f.Port).FirstOrDefault().ToString();
                string Password = db.FromUsers.Where(f => f.EmailAddress.Equals(txt_ComName2.Text.Trim()) && f.user_id.Equals(int.Parse(CommonLogic.GetSessionValue("user_id").ToString()))).Select(f => f.Password).FirstOrDefault();
                bool EnableSSl = db.FromUsers.Where(f => f.EmailAddress.Equals(txt_ComName2.Text.Trim()) && f.user_id.Equals(int.Parse(CommonLogic.GetSessionValue("user_id").ToString()))).Select(f => f.EnableSSL).FirstOrDefault();
                if ((String)Session["new_flag"] == "True")
                {
                    var searchfromuser = db.FromUsers.Where(f => f.EmailAddress.Equals(txt_ComName2.Text.Trim()) && f.user_id.Equals(int.Parse(CommonLogic.GetSessionValue("user_id").ToString()))).Select(f => f).FirstOrDefault();
                    if (searchfromuser != null)
                    {
                        int fromuserid = int.Parse(searchfromuser.Id.ToString());
                        Email myEmail = new Email();
                        myEmail.Title = txt_ComName1.Text.Trim();
                        myEmail.IsDraft = false;
                        myEmail.FromUser = fromuserid;
                        myEmail.ToUser = (touser1 == ',') ? ToUser.TrimEnd(',') : ToUser;
                        if (!string.IsNullOrEmpty(Cc))
                        {
                            myEmail.Cc = (cc1 == ',') ? Cc.TrimEnd(',') : Cc;
                        }
                        if (!string.IsNullOrEmpty(Bcc))
                        {
                            myEmail.Bcc = (bcc1 == ',') ? Bcc.TrimEnd(',') : Bcc;
                        }
                        myEmail.Body = CKEditor1.Text.Trim();
                        myEmail.IsFileAttached = FileAttached;
                        myEmail.SentDateTime = DateTime.Now;
                        myEmail.user_id = int.Parse(CommonLogic.GetSessionValue("user_id").ToString());
                        db.Emails.InsertOnSubmit(myEmail);
                        db.SubmitChanges();
                        int newId = int.Parse(myEmail.Id.ToString());
                        HttpFileCollection fileCollection = Request.Files;
                        double tot_file_size = 0;
                        for (int i = 0; i < fileCollection.Count; i++)
                        {
                            File myFile = new File();
                            HttpPostedFile uploadfile = fileCollection[i];
                            string fileTitle = Path.GetFileName(uploadfile.FileName);
                            string fileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");
                            string fileType = System.IO.Path.GetExtension(fileTitle).ToString().ToLower();
                            myFile.Email_Id = newId;
                            myFile.File_Title = fileTitle;
                            myFile.File_name = fileName;
                            myFile.File_ext = fileType;
                            double file_size = int.Parse(uploadfile.ContentLength.ToString()) / 1024;
                            tot_file_size += file_size;
                            myFile.File_Size = file_size;
                            if (uploadfile.ContentLength > 0)
                            {
                                uploadfile.SaveAs(Server.MapPath("~/EmailFiles/") + fileName + fileType);
                                db.Files.InsertOnSubmit(myFile);
                                db.SubmitChanges();
                                file_names.Add(fileName + fileType);
                            }
                        }
                        db.UpdateEmailField(newId, "TotalFileSize", tot_file_size.ToString());
                        string sbody = ConvertAllString(CKEditor1.Text.Trim());
                        DAL_General.SendReplyMail(newId, txt_ComName1.Text.Trim(), Host, Port, EnableSSl, Email, Password, (touser1 == ',') ? ToUser.TrimEnd(',') : ToUser, (cc1 == ',') ? Cc.TrimEnd(',') : Cc, (bcc1 == ',') ? Bcc.TrimEnd(',') : Bcc, sbody, file_names.ToList(), int.Parse(CommonLogic.GetSessionValue("user_id").ToString()), templateId);
                        int Subcount = 0;
                        string toUser = (touser1 == ',') ? ToUser.TrimEnd(',') : ToUser;
                        if (toUser.Contains(","))
                        {
                            string[] values = ToUser.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                            for (int s = 0; s < values.Length; s++)
                            {
                                Subcount++;
                            }
                        }
                        else
                        {
                            Subcount = 1;
                        }
                        string Ccs = (cc1 == ',') ? Cc.TrimEnd(',') : Cc;
                        if (!string.IsNullOrEmpty(txt_ComName4.Text.Trim()))
                        {
                            string[] values1 = Ccs.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                            for (int c = 0; c < values1.Length; c++)
                            {
                                Subcount++;
                            }
                        }
                        string Bccs = (bcc1 == ',') ? Bcc.TrimEnd(',') : Bcc;
                        if (!string.IsNullOrEmpty(txt_ComName5.Text.Trim()))
                        {
                            string[] values2 = Bccs.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                            for (int b = 0; b < values2.Length; b++)
                            {
                                Subcount++;
                            }
                        }
                        db.ExecuteCommand(@"UPDATE [dbo].[tbl_From_master] SET [SentDateTime] = GETDATE() WHERE [Id]='" + fromuserid + "'");
                        db.ExecuteCommand(@"UPDATE [dbo].[tbl_From_master] SET [Count] = '" + Subcount + "' WHERE [Id]='" + fromuserid + "'");
                        var loggedMessage = db.LoggedMessages.Where(l => l.email_id.Equals(newId)).Select(l => l).ToList();
                        foreach (var message in loggedMessage)
                        {
                            if (message.Sent == true)
                            {
                                ShowAlert("Mail Sent Successfully.", this);
                            }
                            else if (message.Sent == false)
                            {
                                ShowAlert(message.SmtpException.ToString() + "&nbsp;&nbsp;" + message.InnerExceptionDetails.ToString(), this);
                            }
                        }
                    }
                    else
                    {
                        ShowAlert("From User doesn't exist in record.", this);
                    }
                    CommonLogic.SetSessionValue("flag","");
                    CommonLogic.SetSessionValue("commandName", "Outbox");
                    Response.Redirect("mail1.aspx");
                }
                else if ((String)Session["new_flag"] == "False")
                {
                    var searchfromuser = db.FromUsers.Where(f => f.EmailAddress.Equals(txt_ComName2.Text.Trim()) && f.user_id.Equals(int.Parse(CommonLogic.GetSessionValue("user_id").ToString()))).Select(f => f).FirstOrDefault();


//here I just want to check mail subscribers from Touser,Cc,Bcc count less or equals current Count field and time between SentDatetime and CurrentDatetime less or equals one hour


                    if (searchfromuser != null)
                    {
                        int fromuserid = int.Parse(searchfromuser.Id.ToString());
                        db.UpdateEmail(int.Parse(email_id.Value.ToString()), txt_ComName1.Text.Trim(), fromuserid, (touser1 == ',') ? ToUser.TrimEnd(',') : ToUser, (cc1 == ',') ? Cc.TrimEnd(',') : Cc, (bcc1 == ',') ? Bcc.TrimEnd(',') : Bcc, CKEditor1.Text.Trim(), FileAttached, DateTime.Parse(System.DateTime.Now.ToString()));
                        db.SubmitChanges();
                        HttpFileCollection fileCollection = Request.Files;
                        double tot_file_size = 0;
                        for (int i = 0; i < fileCollection.Count; i++)
                        {
                            File myFile = new File();
                            HttpPostedFile uploadfile = fileCollection[i];
                            string fileTitle = Path.GetFileName(uploadfile.FileName);
                            string fileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");
                            string fileType = System.IO.Path.GetExtension(fileTitle).ToString().ToLower();
                            myFile.Email_Id = int.Parse(email_id.Value.ToString());
                            myFile.File_Title = fileTitle;
                            myFile.File_name = fileName;
                            myFile.File_ext = fileType;
                            double file_size = int.Parse(uploadfile.ContentLength.ToString()) / 1024;
                            tot_file_size += file_size;
                            myFile.File_Size = file_size;
                            if (uploadfile.ContentLength > 0)
                            {
                                uploadfile.SaveAs(Server.MapPath("~/EmailFiles/") + fileName + fileType);
                                db.Files.InsertOnSubmit(myFile);
                                db.SubmitChanges();
                                file_names.Add(fileName + fileType);
                            }
                        }
                        var fileNames = db.Files.Where(f => f.Email_Id.Equals(int.Parse(email_id.Value.ToString()))).Select(f => f).ToList();
                        if (fileNames.Count > 0)
                        {
                            foreach (var item in fileNames)
                            {
                                file_names.Add(item.File_name.ToString() + item.File_ext.ToString());
                            }
                        }
                        db.UpdateEmailField(int.Parse(email_id.Value.ToString()), "TotalFileSize", tot_file_size.ToString());
                        string sbody = ConvertAllString(CKEditor1.Text.Trim());
                        DAL_General.SendReplyMail(int.Parse(email_id.Value.ToString()), txt_ComName1.Text.Trim(), Host, Port, EnableSSl, Email, Password, (touser1 == ',') ? ToUser.TrimEnd(',') : ToUser, (cc1 == ',') ? Cc.TrimEnd(',') : Cc, (bcc1 == ',') ? Bcc.TrimEnd(',') : Bcc, sbody, file_names.ToList(), int.Parse(CommonLogic.GetSessionValue("user_id").ToString()), templateId);
                        int Subcount = 0;
                        string toUser = (touser1 == ',') ? ToUser.TrimEnd(',') : ToUser;
                        if (toUser.Contains(","))
                        {
                            string[] values = ToUser.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                            for (int s = 0; s < values.Length; s++)
                            {
                                Subcount++;
                            }
                        }
                        else
                        {
                            Subcount = 1;
                        }
                        string Ccs = (cc1 == ',') ? Cc.TrimEnd(',') : Cc;
                        if (!string.IsNullOrEmpty(txt_ComName4.Text.Trim()))
                        {
                            string[] values1 = Ccs.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                            for (int c = 0; c < values1.Length; c++)
                            {
                                Subcount++;
                            }
                        }
                        string Bccs = (bcc1 == ',') ? Bcc.TrimEnd(',') : Bcc;
                        if (!string.IsNullOrEmpty(txt_ComName5.Text.Trim()))
                        {
                            string[] values2 = Bccs.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                            for (int b = 0; b < values2.Length; b++)
                            {
                                Subcount++;
                            }
                        }
                        db.ExecuteCommand(@"UPDATE [dbo].[tbl_From_master] SET [SentDateTime] = '" + DateTime.Now.Date.ToString() + "' WHERE [Id]='" + fromuserid + "'");
                        db.ExecuteCommand(@"UPDATE [dbo].[tbl_From_master] SET [Count] = '" + Subcount.ToString() + "' WHERE [Id]='" + fromuserid + "'");
                        var loggedMessage = db.LoggedMessages.Where(l => l.email_id.Equals(int.Parse(email_id.Value.ToString()))).Select(l => l).ToList();
                        foreach (var message in loggedMessage)
                        {
                            if (message.Sent == true)
                            {
                                ShowAlert("Mail Sent Successfully.", this);
                            }
                            else if (message.Sent == false)
                            {
                                ShowAlert(message.SmtpException.ToString() + "&nbsp;&nbsp;" + message.InnerExceptionDetails.ToString(), this);
                            }
                        }
                    }
                }
                CommonLogic.SetSessionValue("flag", "");
                CommonLogic.SetSessionValue("commandName", "Outbox");
                Response.Redirect("mail1.aspx");
            }
        }

我刚刚在 google 上搜索并找到了一些解决方案 VB.Net 具有函数 DateDiff 如何使用 c#.net 实现?

------------------------------------更新-- ------------------------------

using (DataClassesDataContext db = new DataClassesDataContext())
        {
            DateTime? LastSentEmailDate = db.FromUsers.Where(f => f.EmailAddress.Equals(txt_ComName2.Text.Trim()) && f.user_id.Equals(int.Parse(CommonLogic.GetSessionValue("user_id").ToString()))).Select(f => f.SentDateTime).FirstOrDefault();
            if (LastSentEmailDate != null)
            {
                DateTime CurrentDate = DateTime.Now;
                int diffTimes = Convert.ToInt32((TimeSpan)(CurrentDate - LastSentEmailDate)); //difference as time you can use as miliseconds interval.TotalMilliSeconds        //this lines gives error
                if (diffTimes <= 3600000)
                {
                    string fromName = db.FromUsers.Where(f => f.EmailAddress.Equals(txt_ComName2.Text.Trim()) && f.user_id.Equals(int.Parse(CommonLogic.GetSessionValue("user_id").ToString()))).Select(f => f.Name).FirstOrDefault();
                    string Email = db.FromUsers.Where(f => f.EmailAddress.Equals(txt_ComName2.Text.Trim()) && f.user_id.Equals(int.Parse(CommonLogic.GetSessionValue("user_id").ToString()))).Select(f => f.EmailAddress).FirstOrDefault();
                    string Host = db.FromUsers.Where(f => f.EmailAddress.Equals(txt_ComName2.Text.Trim()) && f.user_id.Equals(int.Parse(CommonLogic.GetSessionValue("user_id").ToString()))).Select(f => f.Host).FirstOrDefault();
                    string Port = db.FromUsers.Where(f => f.EmailAddress.Equals(txt_ComName2.Text.Trim()) && f.user_id.Equals(int.Parse(CommonLogic.GetSessionValue("user_id").ToString()))).Select(f => f.Port).FirstOrDefault().ToString();
                    string Password = db.FromUsers.Where(f => f.EmailAddress.Equals(txt_ComName2.Text.Trim()) && f.user_id.Equals(int.Parse(CommonLogic.GetSessionValue("user_id").ToString()))).Select(f => f.Password).FirstOrDefault();
                    bool EnableSSl = db.FromUsers.Where(f => f.EmailAddress.Equals(txt_ComName2.Text.Trim()) && f.user_id.Equals(int.Parse(CommonLogic.GetSessionValue("user_id").ToString()))).Select(f => f.EnableSSL).FirstOrDefault();
                    if ((String)Session["new_flag"] == "True")
                    {

在 C# 中,您可以使用 TimeSpan 进行所有这些类型的操作,实际上仅此一项就足够了

用法示例:

DateTime d1 = new DateTime(2019,4,7,13,59,0); //13 days ago 
DateTime d2 = DateTime.Now;  
int diffDays = ((TimeSpan) (date2 - date1)).Days; //difference as day
int diffTimes = ((TimeSpan) (date2 - date1)); //difference as time you can use as miliseconds interval.TotalMilliSeconds

也可以参考C#环境使用Microsoft.VisualBasic.dll