예제 #1
0
        /// <summary>
        /// 修改FTP连接信息
        /// </summary>
        /// <param name="mailFtp"></param>
        public static void UpdateMailFtp(MailFtp mailFtp)
        {
            try
            {
                using (SQLiteConnection conn = new SQLiteConnection(ConfigurationManager.AppSettings["conn"]))
                {
                    conn.Open();
                    using (SQLiteCommand cmd = new SQLiteCommand(conn))
                    {
                        cmd.CommandText = string.Format(@"update MailFtp set FtpDesc=@FtpDesc, FtpServer=@FtpServer, UserName=@UserName, Password=@Password, DefaultPath=@DefaultPath where ID=@ID;");
                        cmd.Parameters.Add(new SQLiteParameter("@FtpDesc", mailFtp.FtpDesc));
                        cmd.Parameters.Add(new SQLiteParameter("@FtpServer", mailFtp.FtpServer));
                        cmd.Parameters.Add(new SQLiteParameter("@UserName", mailFtp.UserName));
                        cmd.Parameters.Add(new SQLiteParameter("@Password", mailFtp.Password));
                        cmd.Parameters.Add(new SQLiteParameter("@DefaultPath", mailFtp.DefaultPath));
                        cmd.Parameters.Add(new SQLiteParameter("@ID", mailFtp.Id));

                        cmd.ExecuteNonQuery();
                    } //eof cmd
                }     //eof cn
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
예제 #2
0
        /// <summary>
        /// 删除FTP连接信息
        /// </summary>
        /// <param name="mailFtp"></param>
        public static void DelMailFtp(MailFtp mailFtp)
        {
            try
            {
                using (SQLiteConnection conn = new SQLiteConnection(ConfigurationManager.AppSettings["conn"]))
                {
                    conn.Open();
                    using (SQLiteCommand cmd = new SQLiteCommand(conn))
                    {
                        // 判断是否有产品用到此连接,有的话不允许删除
                        cmd.CommandText = string.Format(@"select count(1) from ProductAttachment where FtpID=@FtpID;");
                        cmd.Parameters.Add(new SQLiteParameter("@FtpID", mailFtp.Id));
                        int iCount = int.Parse(cmd.ExecuteScalar().ToString());
                        if (iCount > 0)
                        {
                            throw new Exception("目前仍有产品从此FTP下载文件, 无法删除!");
                        }

                        cmd.Parameters.Clear();
                        cmd.CommandText = string.Format(@"delete from MailFtp where ID=@ID;");
                        cmd.Parameters.Add(new SQLiteParameter("@ID", mailFtp.Id));

                        cmd.ExecuteNonQuery();
                    } //eof cmd
                }     //eof cn
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
예제 #3
0
        /// <summary>
        /// 新增FTP连接信息
        /// </summary>
        /// <param name="mailFtp"></param>
        public static void AddMailFtp(MailFtp mailFtp)
        {
            try
            {
                using (SQLiteConnection conn = new SQLiteConnection(ConfigurationManager.AppSettings["conn"]))
                {
                    conn.Open();
                    using (SQLiteCommand cmd = new SQLiteCommand(conn))
                    {
                        cmd.CommandText = string.Format(@"insert into MailFtp (FtpDesc, FtpServer, UserName, Password, DefaultPath) values (@FtpDesc, @FtpServer, @UserName, @Password, @DefaultPath);");
                        cmd.Parameters.Add(new SQLiteParameter("@FtpDesc", mailFtp.FtpDesc));
                        cmd.Parameters.Add(new SQLiteParameter("@FtpServer", mailFtp.FtpServer));
                        cmd.Parameters.Add(new SQLiteParameter("@UserName", mailFtp.UserName));
                        cmd.Parameters.Add(new SQLiteParameter("@Password", mailFtp.Password));
                        cmd.Parameters.Add(new SQLiteParameter("@DefaultPath", mailFtp.DefaultPath));

                        cmd.ExecuteNonQuery();
                    } //eof cmd
                }     //eof cn
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
예제 #4
0
        /// <summary>
        /// ftp文件是否存在
        /// </summary>
        /// <param name="ftpPath"></param>
        /// <param name="ftpInfo"></param>
        private void IsFtpFileExist(string ftpPath, MailFtp ftpInfo)
        {
            FtpWebRequest reqFTP;

            try
            {
                reqFTP             = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
                reqFTP.Method      = WebRequestMethods.Ftp.GetFileSize;
                reqFTP.UseBinary   = true;
                reqFTP.UsePassive  = false;
                reqFTP.Credentials = new NetworkCredential(ftpInfo.UserName, ftpInfo.Password);
                using (FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse())
                {
                }
            }
            catch (WebException ex)
            {
                FtpWebResponse response = (FtpWebResponse)ex.Response;
                switch (response.StatusCode)
                {
                case FtpStatusCode.ActionNotTakenFileUnavailable:
                    throw new Exception(string.Format(@"文件[{0}]不存在", ftpPath));

                case FtpStatusCode.NotLoggedIn:
                    throw new Exception("无法登录FTP, 请检查连接串");

                default:
                    throw new Exception(ex.Message);
                }
            }
        }
예제 #5
0
        public MailFtpEditDialog(Manager mgr, MailFtp mailFtp)
        {
            InitializeComponent();

            _manager = mgr;
            _mailFtp = mailFtp;

            ResetDialog();
        }
예제 #6
0
 private void menuFtpEdit_Click(object sender, EventArgs e)
 {
     if (lvFtpList.SelectedItems.Count > 0)
     {
         ListViewItem lvi = lvFtpList.SelectedItems[0];
         if (lvi != null)
         {
             MailFtp mailFtp = (MailFtp)lvi.Tag;
             using (MailFtpEditDialog dlg = new MailFtpEditDialog(Manager, mailFtp))
             {
                 if (dlg.ShowDialog() == DialogResult.OK)
                 {
                     Manager.ReloadFtpList();
                     ResetDialog();
                 }
             }
         }
     }
 }
예제 #7
0
        /// <summary>
        /// 按照id读ftp
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static MailFtp ReadMailFtp(int id)
        {
            MailFtp mailFtp;

            try
            {
                using (SQLiteConnection cn = new SQLiteConnection(ConfigurationManager.AppSettings["conn"]))
                {
                    cn.Open();

                    using (SQLiteCommand cmd = new SQLiteCommand(cn))
                    {
                        cmd.CommandText = "select * from MailFtp where ID=@ID";
                        cmd.Parameters.Add(new SQLiteParameter("@ID", id));
                        using (SQLiteDataReader dr = cmd.ExecuteReader())
                        {
                            if (!dr.HasRows)
                            {
                                throw new Exception("无数据");
                            }

                            dr.Read();

                            // 获取产品基本信息
                            string ftpDesc     = dr["FtpDesc"].ToString();
                            string ftpServer   = dr["FtpServer"].ToString();
                            string userName    = dr["UserName"].ToString();
                            string password    = dr["Password"].ToString();
                            string defaultPath = dr["DefaultPath"].ToString();

                            mailFtp = new MailFtp(id, ftpDesc, ftpServer, userName, password, defaultPath);
                        } //eof dr
                    }     //eof cmd
                }         //eof conn
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            return(mailFtp);
        }
예제 #8
0
        /// <summary>
        /// 下载ftp文件
        /// </summary>
        /// <param name="ftpPath"></param>
        /// <param name="filePath"></param>
        /// <param name="ftpInfo"></param>
        private void DownloadFtpFile(string ftpPath, string filePath, MailFtp ftpInfo)
        {
            IsFtpFileExist(ftpPath, ftpInfo);

            FtpWebRequest reqFTP;

            try
            {
                using (FileStream outputStream = new FileStream(filePath, FileMode.Create))
                {
                    reqFTP             = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
                    reqFTP.Method      = WebRequestMethods.Ftp.DownloadFile;
                    reqFTP.UseBinary   = true;
                    reqFTP.UsePassive  = false;
                    reqFTP.Credentials = new NetworkCredential(ftpInfo.UserName, ftpInfo.Password);
                    using (FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse())
                    {
                        using (Stream ftpStream = response.GetResponseStream())
                        {
                            long   cl         = response.ContentLength;
                            int    bufferSize = 2048;
                            int    readCount;
                            byte[] buffer = new byte[bufferSize];

                            readCount = ftpStream.Read(buffer, 0, bufferSize);
                            while (readCount > 0)
                            {
                                outputStream.Write(buffer, 0, readCount);
                                readCount = ftpStream.Read(buffer, 0, bufferSize);
                            }
                            ftpStream.Close();
                        }
                        response.Close();
                    }
                    outputStream.Close();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
예제 #9
0
        /// <summary>
        /// 读取FTP列表
        /// </summary>
        /// <returns></returns>
        public static MailFtpList ReadMailFtpList()
        {
            MailFtpList mailFtpList = new MailFtpList();

            try
            {
                using (SQLiteConnection cn = new SQLiteConnection(ConfigurationManager.AppSettings["conn"]))
                {
                    cn.Open();

                    string query = "select * from MailFtp";
                    using (SQLiteCommand cmd = new SQLiteCommand(query, cn))
                    {
                        using (SQLiteDataReader dr = cmd.ExecuteReader())
                        {
                            while (dr.Read())
                            {
                                // 获取产品基本信息
                                int    id          = int.Parse(dr["ID"].ToString());
                                string ftpDesc     = dr["FtpDesc"].ToString();
                                string ftpServer   = dr["FtpServer"].ToString();
                                string userName    = dr["UserName"].ToString();
                                string password    = dr["Password"].ToString();
                                string defaultPath = dr["DefaultPath"].ToString();

                                MailFtp mailFtp = new MailFtp(id, ftpDesc, ftpServer, userName, password, defaultPath);


                                mailFtpList.Add(mailFtp);
                            } //eof while
                        }     //eof dr
                    }         //eof cmd
                }             //eof conn
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            return(mailFtpList);
        }
예제 #10
0
        private void SaveSettings(CancelEventArgs e)
        {
            DialogResult dr = MessageBox.Show("确定提交修改?", "确定", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (dr == DialogResult.Yes)
            {
                string ftpDesc     = txtFtpDesc.Text.Trim();
                string ftpServer   = txtFtpServer.Text.Trim();
                string userName    = txtUserName.Text.Trim();
                string password    = txtPassword.Text.Trim();
                string defaultPath = txtDefaultPath.Text.Trim();


                // 如果MailFtp为空,则是新增
                if (MailFtp == null)
                {
                    MailFtp mailFtp = new MailFtp(0, ftpDesc, ftpServer, userName, password, defaultPath);
                    MailFtpStorage.AddMailFtp(mailFtp);
                }
                else
                {
                    MailFtp.FtpDesc     = ftpDesc;
                    MailFtp.FtpServer   = ftpServer;
                    MailFtp.UserName    = userName;
                    MailFtp.Password    = password;
                    MailFtp.DefaultPath = defaultPath;

                    MailFtpStorage.UpdateMailFtp(MailFtp);
                }



                MessageBox.Show("保存完成!");
            }
            else
            {
                e.Cancel = true;
            }
        }
예제 #11
0
        private void menuFtpDel_Click(object sender, EventArgs e)
        {
            if (lvFtpList.SelectedItems.Count > 0)
            {
                MailFtp mailFtp = (MailFtp)lvFtpList.SelectedItems[0].Tag;

                DialogResult dr = MessageBox.Show("确定删除此条连接?", "确定", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dr == DialogResult.Yes)
                {
                    try
                    {
                        MailFtpStorage.DelMailFtp(mailFtp);
                        MessageBox.Show("已删除!");
                        Manager.ReloadFtpList();
                        ResetDialog();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
        }
예제 #12
0
        // 发送整个list的邮件
        public void SendMail(ProductList productList, DateTime date, BackgroundWorker bgWorker, DoWorkEventArgs e, int sendInterval)
        {
            // 循环每一个产品
            foreach (Product product in productList)
            {
                if (true == bgWorker.CancellationPending)       // 取消事件
                {
                    e.Cancel = true;
                    return;
                }



                // 0.打标记
                product.IsRunning = true;
                bgWorker.ReportProgress(1);
                Thread.Sleep(40);


                // 20190315增加:发送产品前等待时间,防止QQ邮箱550错误
                // 20190320修改:产品可以单独设置等待时间

                int timeToWait = sendInterval;  // 默认使用全局
                if (product.IsDelay)            // 如果单个产品有要求
                {
                    timeToWait = product.DelaySeconds.Value;
                }

                while (timeToWait > 0)
                {
                    product.Note = string.Format(@"发送前等待{0}秒...", timeToWait);
                    bgWorker.ReportProgress(1);
                    Thread.Sleep(1000);
                    timeToWait--;

                    // 取消事件快速响应
                    if (true == bgWorker.CancellationPending)       // 取消事件
                    {
                        product.Note = string.Format(@"手工取消...");
                        bgWorker.ReportProgress(1);
                        e.Cancel = true;
                        return;
                    }
                }


                if (product.Disable == true)
                {
                    string err = "禁用, 跳过";
                    product.Note      = err;
                    product.IsRunning = false;
                    bgWorker.ReportProgress(1);
                    ProductSendLogStorage.AddSendLog(new ProductSendLog(0,
                                                                        product.Id,
                                                                        string.Empty,
                                                                        date,
                                                                        false,
                                                                        err,
                                                                        DateTime.Now));

                    Thread.Sleep(40);
                    continue;
                }


                #region 1.参数校验
                // 判断附件是否有设置
                if (product.ProductAttachmentList.Count <= 0)
                {
                    string err = "没有设置任何附件, 不发送";
                    product.IsRunning      = false;
                    product.IsAttachmentOK = false;
                    product.IsSendOK       = false;
                    product.Note           = err;
                    ProductSendLogStorage.AddSendLog(new ProductSendLog(0,
                                                                        product.Id,
                                                                        string.Empty,
                                                                        date,
                                                                        false,
                                                                        err,
                                                                        DateTime.Now));

                    bgWorker.ReportProgress(1);
                    continue;
                }

                // 判断收件人是否有设置
                int iReceiverCnt = 0;
                foreach (ProductReceiver receiver in product.ProductReceiverList)
                {
                    if (receiver.ReceiverType == ReceiverType.收件人)
                    {
                        iReceiverCnt++;
                    }
                }
                if (iReceiverCnt <= 0)
                {
                    string err = "没有设置收件人, 不发送";
                    product.IsRunning = false;
                    product.IsSendOK  = false;
                    product.Note      = err;
                    ProductSendLogStorage.AddSendLog(new ProductSendLog(0,
                                                                        product.Id,
                                                                        string.Empty,
                                                                        date,
                                                                        false,
                                                                        err,
                                                                        DateTime.Now));

                    bgWorker.ReportProgress(1);
                    continue;
                }
                #endregion


                #region 2.下载附件
                product.Note = "正在下载附件...";
                bgWorker.ReportProgress(1);

                // 创建临时目录(后需要删文件)
                string tmpFile = Path.Combine(System.Environment.CurrentDirectory, "tmp");
                if (!Directory.Exists(tmpFile))
                {
                    Directory.CreateDirectory(tmpFile);
                }

                // 循环配置下载每一个附件
                List <ProductAttachmentTmp> tmpAttList = new List <ProductAttachmentTmp>();   // 临时文件列表
                try
                {
                    foreach (ProductAttachment att in product.ProductAttachmentList)
                    {
                        string displayPath = Util.ReplaceStringWithDateFormat(att.DisplayPath, date);
                        string actualPath  = string.Empty;
                        bool   isExist     = false;

                        switch (att.Type)
                        {
                        case AttachmentType.磁盘路径:
                            actualPath = displayPath;
                            break;

                        case AttachmentType.FTP:
                            actualPath = Path.Combine(tmpFile, Path.GetFileName(displayPath));
                            // ftp下载
                            MailFtp ftpInfo = MailFtpStorage.ReadMailFtp(att.FtpID.Value);
                            DownloadFtpFile(displayPath, actualPath, ftpInfo);

                            break;
                        }

                        if (!File.Exists(actualPath))
                        {
                            isExist = false;
                        }
                        else
                        {
                            isExist = true;
                        }

                        tmpAttList.Add(new ProductAttachmentTmp(displayPath, actualPath, isExist));
                    }
                }
                catch (Exception ex)
                {
                    // note处写异常
                    string err = string.Format(@"下载附件失败: {0}", ex.Message);
                    product.IsRunning      = false;
                    product.IsAttachmentOK = false;
                    product.IsSendOK       = false;
                    product.Note           = err;
                    ProductSendLogStorage.AddSendLog(new ProductSendLog(0,
                                                                        product.Id,
                                                                        string.Empty,
                                                                        date,
                                                                        false,
                                                                        err,
                                                                        DateTime.Now));

                    bgWorker.ReportProgress(1);
                    continue;
                }


                // 判断附件缺失
                List <string> missingAttachments = new List <string>(); // 缺失文件列表
                foreach (ProductAttachmentTmp tmpAttr in tmpAttList)    //要改
                {
                    if (tmpAttr.IsExist == false)
                    {
                        missingAttachments.Add(tmpAttr.DisplayPath);
                    }
                }
                if (missingAttachments.Count > 0)
                {
                    product.IsRunning      = false;
                    product.IsAttachmentOK = false;
                    product.IsSendOK       = false;

                    StringBuilder sbAttachments = new StringBuilder();
                    foreach (string att in missingAttachments)
                    {
                        if (sbAttachments.Length > 0)
                        {
                            sbAttachments.Append(";");
                        }
                        sbAttachments.Append(att);
                    }

                    string err = "附件缺失: " + sbAttachments.ToString();

                    product.Note = err;                                         // 写日志
                    ProductSendLogStorage.AddSendLog(new ProductSendLog(0,
                                                                        product.Id,
                                                                        string.Empty,
                                                                        date,
                                                                        false,
                                                                        err,
                                                                        DateTime.Now));

                    bgWorker.ReportProgress(1);
                    continue;
                }
                else
                {
                    product.Note           = "附件下载完成";
                    product.IsAttachmentOK = true;
                    product.Note           = string.Empty; // 可以具体一点
                    bgWorker.ReportProgress(1);
                }
                Thread.Sleep(40);
                #endregion



                #region 3.开始发送邮件
                // SmtpClient对象
                SmtpClient client = new SmtpClient();
                client.Host        = MailSender.Host;           // smtp服务器
                client.Port        = MailSender.Port;           // smtp端口
                client.EnableSsl   = MailSender.EnableSSL;      // ssl加密
                client.Credentials = new System.Net.NetworkCredential(MailSender.Address, MailSender.Password);
                client.Timeout     = MailSender.Timeout * 1000; // 超时时间


                // msg对象
                MailMessage msg = new MailMessage();
                msg.From            = new MailAddress(MailSender.Address, MailSender.DisplayName, Encoding.UTF8);           // 发件人信息
                msg.Subject         = Util.ReplaceStringWithDateFormat(product.MailTitle, date);                            // 邮件标题
                msg.SubjectEncoding = System.Text.Encoding.UTF8;                                                            // 邮件标题编码
                msg.Body            = Util.ReplaceStringWithDateFormat(product.MailContent + MailSender.TailContent, date); //邮件内容
                msg.BodyEncoding    = System.Text.Encoding.UTF8;                                                            // 邮件内容编码
                msg.IsBodyHtml      = false;                                                                                // 是否是HTML邮件
                msg.Priority        = MailSender.Priority;                                                                  // 邮件优先级



                // 添加收件人
                foreach (ProductReceiver receiver in product.ProductReceiverList)
                {
                    switch (receiver.ReceiverType)
                    {
                    case ReceiverType.收件人:
                        msg.To.Add(receiver.EmailAddress);
                        break;

                    case ReceiverType.抄送:
                        msg.CC.Add(receiver.EmailAddress);
                        break;

                    case ReceiverType.密送:
                        msg.Bcc.Add(receiver.EmailAddress);
                        break;

                    default:
                        msg.To.Add(receiver.EmailAddress);
                        break;
                    }
                }

                // 添加附件
                foreach (ProductAttachmentTmp attTmp in tmpAttList)
                {
                    msg.Attachments.Add(new Attachment(attTmp.ActualPath));
                }


                try
                {
                    product.Note = "正在发送...";
                    bgWorker.ReportProgress(1);


                    ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return(true); };

                    client.Send(msg);
                    //client.SendAsync(msg, userState);

                    product.IsSendOK = true;
                    product.Note     = "发送完成";
                    bgWorker.ReportProgress(1);

                    ProductSendLogStorage.AddSendLog(new ProductSendLog(0,
                                                                        product.Id,
                                                                        string.Empty,
                                                                        date,
                                                                        true,
                                                                        "发送完成",
                                                                        DateTime.Now));
                }
                catch (Exception ex)
                {
                    product.IsRunning = false;
                    product.IsSendOK  = false;
                    product.Note      = "发送失败:" + ex.Message;    // 可以具体一点
                                                                 // 写日志
                    bgWorker.ReportProgress(1);

                    ProductSendLogStorage.AddSendLog(new ProductSendLog(0,
                                                                        product.Id,
                                                                        string.Empty,
                                                                        date,
                                                                        false,
                                                                        "发送失败:" + ex.Message,
                                                                        DateTime.Now));
                    continue;
                }
                finally
                {
                    if (msg != null)
                    {
                        msg.Dispose();
                    }
                }

                #endregion


                // 3.发完更新数据库时间戳,写日志


                // 4.收尾
                product.IsRunning = false;
                bgWorker.ReportProgress(1);
            }


            // 删除tmp目录
            try
            {
                string tmpFile = Path.Combine(System.Environment.CurrentDirectory, "tmp");
                if (Directory.Exists(tmpFile))
                {
                    Directory.Delete(tmpFile, true);
                }
            }
            catch (Exception)
            { }
        }