Example #1
0
        /// <summary>
        /// 修改占用
        /// </summary>
        public bool UpdateEmailAccountOccupy(EmailAccountEntity model)
        {
            Dictionary <string, object> dic = new Dictionary <string, object>();

            dic["EmailAccountID"] = model.EmailAccountID;
            dic["OccupyIP"]       = model.OccupyIP;
            return(SQLHelperFactory.Instance.ExecuteNonQuery("UpdateEmailAccount_Occupy", dic) > 0);
        }
Example #2
0
        /// <summary>
        /// 修改
        /// </summary>
        public bool Update(EmailAccountEntity model)
        {
            Dictionary <string, object> dic = new Dictionary <string, object>();

            dic["EmailAccountID"]            = model.EmailAccountID;
            dic["EmailAccountAddress"]       = model.EmailAccountAddress;
            dic["EmailAccountPassWord"]      = model.EmailAccountPassWord;
            dic["EmailAccountName"]          = model.EmailAccountName;
            dic["EmailAccountSMTP"]          = model.EmailAccountSMTP;
            dic["EmailAccountSMTPPort"]      = model.EmailAccountSMTPPort;
            dic["EmailAccountPOP3"]          = model.EmailAccountPOP3;
            dic["EmailAccountPOP3Port"]      = model.EmailAccountPOP3Port;
            dic["EmailAccountIsSSL"]         = model.EmailAccountIsSSL;
            dic["EmailAccountMaxEmailCount"] = model.EmailAccountMaxEmailCount;
            dic["EmailAccountSpace"]         = model.EmailAccountSpace;
            dic["SendState"] = model.SendState;
            dic["SendMode"]  = model.SendMode;
            dic["EmailAccountCategoryID"]   = model.EmailAccountCategoryID;
            dic["EmailAccountCategoryName"] = model.EmailAccountCategoryName;
            return(SQLHelperFactory.Instance.ExecuteNonQuery("Update_emailaccount", dic) > 0);
        }
Example #3
0
        public bool SendEmail(MailMessage message, EmailAccountEntity emailAccount)
        {
            try {
                var smtpClient = new SmtpClient {
                    EnableSsl             = emailAccount.SslEnabled,
                    Host                  = emailAccount.Host,
                    Port                  = emailAccount.Port,
                    UseDefaultCredentials = emailAccount.UseDefaultCredentials,
                    Credentials           = new NetworkCredential(emailAccount.UserName, emailAccount.Password),
                };

                smtpClient.Send(message);

                _logService.Information("A new message was sent.");

                return(true);
            } catch (Exception exception) {
                _logService.Error("An error occured when sending a message", exception);

                return(false);
            }
        }
        public void Run(EmailAccountEntity emailAccount)
        {
            EmailAccount = emailAccount;
            //Interval = emailAccount.EmailAccountSpace * 60;
            if (!IsStart)
            {
                IsStart = true;
                _Thread = new Thread((s) =>
                {
                    while (IsStart)
                    {
                        try
                        {
                            //每一次賦值為10秒
                            Interval = 10;
                            //1. 重新获取邮箱信息,判断邮箱是否被占用,如果占用时间太久并不进行发送操作可以认为已经异常结束占用
                            EmailAccount = EA_Repository.Get(EmailAccount.EmailAccountID);
                            if (EmailAccount == null)
                            {
                                LogHelper.Info(string.Format("SmartSendEmail : 发件箱【{0}:{1}】不存在", emailAccount.EmailAccountID, emailAccount.EmailAccountAddress));
                                //占用失败,退出线程
                                IsStart = false;
                                break;
                            }
                            //2. 修改邮箱使用的服务器信息-增加占用信息和占用时间
                            EmailAccount.OccupyIP = NetHelper.LANIP;
                            LogHelper.Debug(string.Format("SmartSendEmail : 准备继续占用发件箱【{0}:{1}】的IP【{2} -> {3}】", EmailAccount.EmailAccountID, EmailAccount.EmailAccountAddress, EmailAccount.OccupyIP, NetHelper.LANIP));
                            if (!EA_Repository.UpdateEmailAccountOccupy(EmailAccount))
                            {
                                LogHelper.Info(string.Format("SmartSendEmail : 继续占用发件箱【{0}:{1}】的IP【{2} -> {3}】失败,已被其他占用", EmailAccount.EmailAccountID, EmailAccount.EmailAccountAddress, EmailAccount.OccupyIP, NetHelper.LANIP));
                                //占用失败,退出线程
                                IsStart = false;
                                break;
                            }
                            LogHelper.Debug(string.Format("SmartSendEmail : 发件箱【{0}:{1}】下一次发送时间和数量为【{2} -> {3}】", EmailAccount.EmailAccountID, EmailAccount.EmailAccountAddress, EmailAccount.EmailAccountNextSendTime, EmailAccount.EmailAccountRemainEmailCount));
                            //3. 判断下一次发送时间和当期时间对比
                            if (EmailAccount.EmailAccountNextSendTime >= DateTime.Now)
                            {
                                //还没到时间执行
                                Interval = (EmailAccount.EmailAccountNextSendTime - DateTime.Now).Seconds + 1;
                                if (Interval > (EmailAccount.EmailAccountSpace * 60 / 3))
                                {
                                    Interval = (EmailAccount.EmailAccountSpace * 60 / 3);
                                }
                                if (Interval <= 0)
                                {
                                    Interval = 10;
                                }
                                continue;
                            }
                            //本次可發送的數量
                            var sendCount = EmailAccount.EmailAccountRemainEmailCount;
                            //如果减少了最大发送数量,或者上一次发送离现在已经超过一个间隔,或者下一次发送已经过去一个间隔
                            if (sendCount > EmailAccount.EmailAccountMaxEmailCount ||
                                EmailAccount.EmailAccountPreSendTime.AddMinutes(EmailAccount.EmailAccountSpace) < DateTime.Now || emailAccount.EmailAccountNextSendTime.AddMinutes(EmailAccount.EmailAccountSpace) < DateTime.Now)
                            {
                                sendCount = EmailAccount.EmailAccountMaxEmailCount;
                            }
                            LogHelper.Debug(string.Format("SmartSendEmail : 发件箱【{0}:{1}】可发送实际数量为【{2}】", EmailAccount.EmailAccountID, EmailAccount.EmailAccountAddress, sendCount));
                            //if (sendCount <= 0)
                            //{
                            //    continue;
                            //}
                            //4. 获取发送列表,按照指定数量获取
                            //先获取已分配但是未发送的
                            var emailInfo = E_Repository.GetAssignSendEmailInfoByEmailAccount(EmailAccount.EmailAccountID);
                            if (emailInfo == null || emailInfo.EmailID <= 0)
                            {
                                //获取发送中还没开始分配的
                                emailInfo = E_Repository.GetNextSendEmailInfoByEmailAccount(EmailAccount.EmailAccountID);
                            }
                            else
                            {
                                LogHelper.Info(string.Format("SmartSendEmail : 发件箱【{0}:{1}】准备发送上次分配未发送的邮件【{2} ->{3}】", EmailAccount.EmailAccountID, EmailAccount.EmailAccountAddress, emailInfo.EmailID, emailInfo.EmailTitle));
                            }
                            if (emailInfo == null || emailInfo.EmailID <= 0)
                            {
                                LogHelper.Debug(string.Format("SmartSendEmail : 发件箱【{0}:{1}】没有待发送的邮件", EmailAccount.EmailAccountID, EmailAccount.EmailAccountAddress, sendCount));
                                //如果本次没需要发送的邮件,则60查看一次
                                Interval = 10;
                                continue;
                            }
                            LogHelper.Info(string.Format("SmartSendEmail : 发件箱【{0}:{1}】准备发送邮件【{2} ->{3}】", EmailAccount.EmailAccountID, EmailAccount.EmailAccountAddress, emailInfo.EmailID, emailInfo.EmailTitle));
                            //分配以及獲取分配好的記錄,防止因上次異常分配導致的分配數量超出可發送數量的問題
                            var sendList = ESB_Repository.GetListByEmailAccountAndEmailID(emailInfo.EmailID, EmailAccount.EmailAccountID, sendCount);
                            if (sendList == null || sendList.Count() <= 0)
                            {
                                LogHelper.Info(string.Format("SmartSendEmail : 发件箱【{0}:{1}】准备发送邮件【{2} ->{3}】时找不到可发送的收件箱", EmailAccount.EmailAccountID, EmailAccount.EmailAccountAddress, emailInfo.EmailID, emailInfo.EmailTitle));
                                //如果本次没需要发送的邮件,则等待10秒马上查看下一个需要发送的邮件
                                Interval = 10;
                                continue;
                            }
                            try
                            {
                                LogHelper.Info(string.Format("SmartSendEmail : 发件箱【{0}:{1}】发送邮件【{2} ->{3}】开始", EmailAccount.EmailAccountID, EmailAccount.EmailAccountAddress, emailInfo.EmailID, emailInfo.EmailTitle));
                                //5. 发送邮件
                                CDOSendEmail cdoSend = new CDOSendEmail();
                                cdoSend.SendEmail(emailInfo, EmailAccount, sendList.ToList());
                                LogHelper.Info(string.Format("SmartSendEmail : 发件箱【{0}:{1}】发送邮件【{2} ->{3}】完成", EmailAccount.EmailAccountID, EmailAccount.EmailAccountAddress, emailInfo.EmailID, emailInfo.EmailTitle));
                            }
                            catch (Exception ex)
                            {
                                if (Constants.ErrorContinueList != null && Constants.ErrorContinueList.Count > 0)
                                {
                                    foreach (var message in Constants.ErrorContinueList)
                                    {
                                        if (ex.Message.IndexOf(message) >= 0)
                                        {
                                            Interval = 60;
                                            throw ex;
                                        }
                                    }
                                }
                                LogHelper.Error(string.Format("SmartSendEmail : 发件箱【{0}:{1}】发送邮件【{2} ->{3}】Exception:{4}", EmailAccount.EmailAccountID, EmailAccount.EmailAccountAddress, emailInfo.EmailID, emailInfo.EmailTitle, ex.Message), ex);
                                foreach (var f in sendList)
                                {
                                    f.EmailSendBccAccountState = -1;
                                    f.Result = ex.Message;
                                }
                            }
                            //6. 记录结果
                            LogHelper.Debug(string.Format("SmartSendEmail : 发件箱【{0}:{1}】发送邮件【{2} ->{3}】完成-修改发送状态", EmailAccount.EmailAccountID, EmailAccount.EmailAccountAddress, emailInfo.EmailID, emailInfo.EmailTitle));
                            ESB_Repository.UpdateState(sendList.ToList());
                            E_Repository.Update_EmaiInfoQTY_ByEmailID(emailInfo.EmailID);
                            List <EmailSendFailureEntity> FailList = new List <EmailSendFailureEntity>();
                            foreach (var f in sendList.Where(l => l.EmailSendBccAccountState == -1))
                            {
                                FailList.Add(new EmailSendFailureEntity()
                                {
                                    EmailID = f.EmailID, EmailAccountID = f.EmailAccountID, EmailBccAccountID = f.EmailBccAccountID, EmailSendFailureSendTime = DateTime.Now, Result = f.Result
                                });
                            }
                            if (FailList != null && FailList.Count > 0)
                            {
                                ESF_Repository.Insert(FailList);
                                LogHelper.Info(string.Format("SmartSendEmail : 发件箱【{0}:{1}】发送邮件【{2} ->{3}】本次发送失败【{4}】", EmailAccount.EmailAccountID, EmailAccount.EmailAccountAddress, emailInfo.EmailID, emailInfo.EmailTitle, FailList.Count));
                            }

                            //7. 修改信息
                            var RemainCount  = sendCount - sendList.Count();
                            var nextSendTime = DateTime.Now;//舍弃一次不足,防止计算重复的问题
                            if (RemainCount <= 0)
                            {
                                if (EmailAccount.EmailAccountSpace > 0)
                                {
                                    nextSendTime = DateTime.Now.AddMinutes(EmailAccount.EmailAccountSpace);
                                }
                                RemainCount = EmailAccount.EmailAccountMaxEmailCount;
                            }
                            LogHelper.Info(string.Format("SmartSendEmail : 发件箱【{0}:{1}】发送邮件【{2} ->{3}】完成,修改发件箱下次发送时间【{4}】,剩余发送数量【{5}】", EmailAccount.EmailAccountID, EmailAccount.EmailAccountAddress, emailInfo.EmailID, emailInfo.EmailTitle, nextSendTime, RemainCount));
                            EA_Repository.UpdateRemainCount(EmailAccount.EmailAccountID, RemainCount, nextSendTime);
                            Interval = 0;
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Error(string.Format("SmartSendEmail : 发件箱【{0}:{1}】 Exception:{2}", EmailAccount.EmailAccountID, EmailAccount.EmailAccountAddress, ex.Message), ex);
                        }
                        finally
                        {
                            SleepInterval(Interval);
                        }
                    }
                });
                _Thread.Start();
            }
        }
Example #5
0
 private void Button_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         if (string.IsNullOrWhiteSpace(txtName.Text.Trim()))
         {
             "请输入名称!".ShowDialog();
             return;
         }
         if (string.IsNullOrWhiteSpace(txtEmailAddress.Text.Trim()) || !MailHelper.IsEmail(txtEmailAddress.Text.Trim()))
         {
             "请输入郵箱地址(郵箱地址要正確)!".ShowDialog();
             return;
         }
         if (string.IsNullOrWhiteSpace(txtPassword.Text.Trim()))
         {
             "请输入密碼!".ShowDialog();
             return;
         }
         if (string.IsNullOrWhiteSpace(txtSMTP.Text.Trim()))
         {
             "请输入SMTP!".ShowDialog();
             return;
         }
         if (string.IsNullOrWhiteSpace(txtPOP3.Text.Trim()))
         {
             "请输入POP3!".ShowDialog();
             return;
         }
         if (string.IsNullOrWhiteSpace(txtSMTPPort.Text.Trim()))
         {
             "请输入SMTP端口!".ShowDialog();
             return;
         }
         if (string.IsNullOrWhiteSpace(txtPOPPort.Text.Trim()))
         {
             "请输入POP3Port端口!".ShowDialog();
             return;
         }
         if (string.IsNullOrWhiteSpace(txtMaxSendCount.Text.Trim()))
         {
             "请输最多發送數量!".ShowDialog();
             return;
         }
         if (string.IsNullOrWhiteSpace(txtInterval.Text.Trim()))
         {
             "请選擇發送間隔!".ShowDialog();
             return;
         }
         var category = this.cbCategory.SelectedItem as EmailAccountCategoryEntity;
         var entity   = EA_Repository.GetByAddress(txtEmailAddress.Text.Trim());
         if (this.EmailAccountID == -1 && entity != null)
         {
             "郵箱已存在,請不要重複添加".ShowDialog();
             return;
         }
         if (this.EmailAccountID != -1 && entity != null && this.EmailAccountID != entity.EmailAccountID)
         {
             "郵箱已存在".ShowDialog();
             return;
         }
         if (this.EmailAccountID == -1)
         {
             entity = new EmailAccountEntity
             {
                 EmailAccountAddress       = txtEmailAddress.Text.Trim(),
                 EmailAccountName          = txtName.Text.Trim(),
                 EmailAccountIsSSL         = cbSSL.SelectedIndex,
                 EmailAccountMaxEmailCount = int.Parse(txtMaxSendCount.Text.Trim()),
                 EmailAccountSpace         = int.Parse(txtInterval.Text.Trim()),
                 EmailAccountPassWord      = txtPassword.Text.Trim(),
                 EmailAccountPOP3          = txtPOP3.Text.Trim(),
                 EmailAccountPOP3Port      = int.Parse(txtPOPPort.Text.Trim()),
                 EmailAccountSMTP          = txtSMTP.Text.Trim(),
                 EmailAccountSMTPPort      = int.Parse(txtSMTPPort.Text.Trim()),
                 SendMode = (this.cbSendMode.Text == "發送" ? 0 : 1),
                 EmailAccountCategoryID   = category.ID,
                 EmailAccountCategoryName = category.Name
             };
             LogHelper.Info(string.Format("新增郵箱【{0}】", entity.EmailAccountAddress));
             EA_Repository.Insert(entity);
             LogHelper.Info(string.Format("新增郵箱【{0}】成功", entity.EmailAccountAddress));
         }
         else
         {
             entity = EA_Repository.Get(this.EmailAccountID);
             entity.EmailAccountAddress       = txtEmailAddress.Text.Trim();
             entity.EmailAccountName          = txtName.Text.Trim();
             entity.EmailAccountIsSSL         = cbSSL.SelectedIndex;
             entity.EmailAccountMaxEmailCount = int.Parse(txtMaxSendCount.Text.Trim());
             entity.EmailAccountSpace         = int.Parse(txtInterval.Text.Trim());
             entity.EmailAccountPassWord      = txtPassword.Text.Trim();
             entity.EmailAccountPOP3          = txtPOP3.Text.Trim();
             entity.EmailAccountPOP3Port      = int.Parse(txtPOPPort.Text.Trim());
             entity.EmailAccountSMTP          = txtSMTP.Text.Trim();
             entity.EmailAccountSMTPPort      = int.Parse(txtSMTPPort.Text.Trim());
             entity.SendMode = (this.cbSendMode.Text == "發送" ? 0 : 1);
             entity.EmailAccountCategoryID   = category.ID;
             entity.EmailAccountCategoryName = category.Name;
             LogHelper.Info(string.Format("修改郵箱【{0}】", entity.EmailAccountAddress));
             EA_Repository.Update(entity);
             LogHelper.Info(string.Format("修改郵箱【{0}】成功", entity.EmailAccountAddress));
         }
         if (this.EmailAccountID == -1)
         {
             "郵箱添加成功!".ShowDialog();
         }
         else
         {
             "郵箱修改成功!".ShowDialog();
         }
         this.DialogResult = true;
         this.Close();
     }
     catch (Exception ex)
     {
         if (this.EmailAccountID == -1)
         {
             LogHelper.Error(string.Format("新增郵箱【{0}】異常", txtEmailAddress.Text.Trim()), ex);
             "郵箱添加失败!".ShowDialog();
         }
         else
         {
             LogHelper.Error(string.Format("修改郵箱【{0}】為【{1}】異常", this.EmailAccountID, txtEmailAddress.Text.Trim()), ex);
             "郵箱修改失败!".ShowDialog();
         }
     }
 }
Example #6
0
        public void SendEmail(EmailInfoEntity emailInfo, EmailAccountEntity emailAccount, List <EmailSendBccAccountEntity> toMails)
        {
            try
            {
                #region 设置基本信息
                CDO.Message oMsg = new CDO.Message();

                Configuration conf = new ConfigurationClass();
                conf.Fields[CdoConfiguration.cdoSendUsingMethod].Value  = CdoSendUsing.cdoSendUsingPort;
                conf.Fields[CdoConfiguration.cdoSMTPAuthenticate].Value = CdoProtocolsAuthentication.cdoBasic;
                conf.Fields[CdoConfiguration.cdoSMTPUseSSL].Value       = emailAccount.EmailAccountIsSSL == 1;
                conf.Fields[CdoConfiguration.cdoSMTPServer].Value       = emailAccount.EmailAccountSMTP;//必填,而且要真实可用
                conf.Fields[CdoConfiguration.cdoSMTPServerPort].Value   = emailAccount.EmailAccountSMTPPort;
                conf.Fields[CdoConfiguration.cdoSendEmailAddress].Value = emailAccount.EmailAccountAddress;
                conf.Fields[CdoConfiguration.cdoSendUserName].Value     = emailAccount.EmailAccountAddress;  //真实的邮件地址
                conf.Fields[CdoConfiguration.cdoSendPassword].Value     = emailAccount.EmailAccountPassWord; //为邮箱密码,必须真实

                conf.Fields.Update();
                oMsg.Configuration = conf;
                #endregion 设置基本信息

                #region htmlbody

                string        bodyStr = emailInfo.EmailFilePath;
                List <string> strList = MailHelper.GetHtmlImageUrlList(bodyStr);
                Dictionary <string, string> dicImage = new Dictionary <string, string>();
                foreach (var str in strList)
                {
                    string key    = Guid.NewGuid().ToString();
                    string newUrl = "cid:" + key;
                    bodyStr = bodyStr.Replace(str, newUrl);
                    dicImage.Add(key, str);
                }
                oMsg.HTMLBody = bodyStr;
                #endregion
                StringBuilder title = new StringBuilder();
                title.Append("=?BIG5?B?");
                title.Append(ToBase64(emailInfo.EmailTitle));
                title.Append("?=");
                oMsg.Subject = title.ToString();
                oMsg.From    = "\"" + emailAccount.EmailAccountName + "\"" + emailAccount.EmailAccountAddress;
                ;//真实的邮件地址
                #region BCC
                StringBuilder bccs = new StringBuilder();
                foreach (EmailSendBccAccountEntity to in toMails)
                {
                    try
                    {
                        //还要加上邮箱的正确性检验
                        if (!string.IsNullOrEmpty(to.EmailBccAccountAddress)) //&& MailHelper.IsEmail(to.EmailBccAccountInfo.EmailBccAccountAddress))
                        {
                            bccs.Append(to.EmailBccAccountAddress + ";");
                            to.EmailSendBccAccountState = 1;
                            to.Result = "成功";
                        }
                        else
                        {
                            to.EmailSendBccAccountState = -1;
                            to.Result = "收件箱地址不正确";
                        }
                    }
                    catch (Exception ex)
                    {
                        to.EmailSendBccAccountState = -1;
                        to.Result = "收件箱地址不正确:" + ex.Message;
                    }
                }

                oMsg.BCC = bccs.ToString();
                #endregion BCC
                oMsg.HTMLBodyPart.Charset = "BIG5";

                foreach (var imgUrl in dicImage)
                {
                    oMsg.AddRelatedBodyPart(imgUrl.Value, imgUrl.Key, CdoReferenceType.cdoRefTypeId);
                }
                lock (SendLock)
                {
                    Constants.SleepInterval(Constants.SendWaitTime);
                    LogHelper.Debug(string.Format("CDOSendEmail 发送邮件开始: 发件箱【{0}:{1}】发送邮件【{2} ->{3}】", emailAccount.EmailAccountID, emailAccount.EmailAccountAddress, emailInfo.EmailID, emailInfo.EmailTitle));
                    oMsg.Send();
                    LogHelper.Debug(string.Format("CDOSendEmail 发送邮件完成: 发件箱【{0}:{1}】发送邮件【{2} ->{3}】完成", emailAccount.EmailAccountID, emailAccount.EmailAccountAddress, emailInfo.EmailID, emailInfo.EmailTitle));
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(string.Format("CDOSendEmail 发送邮件异常: 发件箱【{0}:{1}】发送邮件【{2} ->{3}】Exception:{4}", emailAccount.EmailAccountID, emailAccount.EmailAccountAddress, emailInfo.EmailID, emailInfo.EmailTitle, ex.Message), ex);
                throw ex;
            }
        }