MYSQL自动备份并发送邮件工具

2023-07-19 14:31:29 浏览数 (1)

最近在开发小程序,由于服务器只有一台,所以不能数据库异机备份,出于数据安全的考虑,就做了一个数据库定时备份并发送邮件到自己的邮箱的小工具,先看下工具界面

这个工具主要涉及到三个部分

1.MYSQL自动备份

2.发送邮件

3.定时任务

MYSQL备份可以通过调用mysqldump命令从而来进行备份,这里提供一个命令大全:https://www.jb51.net/article/135724.htm

这里因为工具运行在服务器,所以连接ip和端口就默认为localhost和3306,直接上代码

代码语言:javascript复制
   public static void BackUpDB(string MySqlInstallPath, string BackUpFolderPath, string UserName, string Password, string DataBaseName, ref string BackUpFilePath)
        {
            try
            {
                //String command = "mysqldump --quick --host=localhost --default-character-set=gb2312 --lock-tables --verbose  --force --port=端口号 --user=用户名 --password=密码 数据库名 -r 备份到的地址";
                //构建执行的命令
                StringBuilder sbcommand = new StringBuilder();

                StringBuilder sbfileName = new StringBuilder();
                sbfileName.AppendFormat("{0}", DataBaseName   DateTime.Now.ToShortDateString()).Replace("-", "").Replace(":", "").Replace(" ", "").Replace("/", "");
                String fileName = sbfileName.ToString();
                String directory = BackUpFolderPath   fileName   ".bak";
                BackUpFilePath = directory;
                sbcommand.AppendFormat("mysqldump --quick --host=localhost --default-character-set=utf8 --lock-tables --verbose  --force --port=3306 --user={0} --password={1} {2} -r "{3}"", UserName, Password, DataBaseName, directory);
                String command = sbcommand.ToString();

                //获取mysqldump.exe所在路径
                StartCmd(MySqlInstallPath, command);
                FLog.WriteLog("备份成功!");
                File.Delete(BackUpFilePath);
            }
            catch (Exception ex)
            {
                FLog.WriteLog("备份失败!异常信息:"   ex.Message);
            }
        }

发送邮件部分使用的就是微软自带的基础库,配置stmp服务商域名,和你的邮箱账号,发送邮件授权码。

代码语言:javascript复制
   public static bool SendMail(MailModel model)
        {
            try
            {
                MailAddress receiver = new MailAddress(model.ReceiverAddress, model.ReceiverName);
                MailAddress sender = new MailAddress(model.SenderAddress, model.SenderName);
                MailMessage message = new MailMessage();
                message.From = sender;//发件人
                message.To.Add(receiver);//收件人
                //message.CC.Add(sender);//抄送人
                message.Subject = model.Title;//标题
                message.Body = model.Content;//内容
                message.IsBodyHtml = true;//是否支持内容为HTML

                if (!string.IsNullOrEmpty(model.AttachFilePath))
                {
                    //将文件进行转换成Attachments
                    Attachment data = new Attachment(model.AttachFilePath, MediaTypeNames.Application.Octet);
                    // Add time stamp information for the file.
                    ContentDisposition disposition = data.ContentDisposition;
                    disposition.CreationDate = System.IO.File.GetCreationTime(model.AttachFilePath);
                    disposition.ModificationDate = System.IO.File.GetLastWriteTime(model.AttachFilePath);
                    disposition.ReadDate = System.IO.File.GetLastAccessTime(model.AttachFilePath);
                    message.Attachments.Add(data);
                }
              

                SmtpClient client = new SmtpClient();
                client.Host = "smtp.qq.com";
                //client.Port = 465;
                client.EnableSsl = true;//是否启用SSL
                client.Timeout = 10000;//超时
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = false;
                client.Credentials = new NetworkCredential(model.SenderAddress, model.SenderPassword);
                client.Send(message);
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }

定时任务部分使用Quartz.net,写一个任务类挂在调度器下,不间断运行,时间和自己设置的时分秒一致时执行任务,任务所需要的数据库,邮件等信息可以通过JobDataMap传递,看下简单代码

代码语言:javascript复制
   public static void StartTask(Dictionary<string,string> JobData)
        {
            IScheduler scheduler = GetScheduler();
            IJobDetail job = JobBuilder.Create(Type.GetType("DataBaseBackUpUtil.BackUpJob")).Build();
            TriggerBuilder builder = TriggerBuilder.Create().WithIdentity("定时任务计划", "System");
            //声明具体的执行时间
            builder.WithSimpleSchedule(t =>
                  t.RepeatForever().WithIntervalInSeconds(1));
            ITrigger trigger = builder.Build();
            //传递数据
            foreach (var item in JobData)
            {
                job.JobDataMap.Put(item.Key, item.Value);
            }
            scheduler.ScheduleJob(job, trigger);
            scheduler.Start();
        }

同时该小工具也通过notifyIcon组件达到可以缩小化至提示栏中防止误操作关闭。

项目地址:MYSQL数据自动备份并发送邮件工具: MYSQL自动定时备份并发送数据备份文件至指定邮箱

更新20181220 修复问题

1.因为服务器厂商默认屏蔽25端口,所以需要使用ssl加密465端口发送,但是System.Net.Mail不支持ssl,所以要换成System.Web.Mail下的类进行发送,代码如下

代码语言:javascript复制
 public static bool SendMail(MailModel model)
        {
            try
            {
                System.Web.Mail.MailMessage mmsg = new System.Web.Mail.MailMessage();
                //邮件主题
                mmsg.Subject = model.Title;
                mmsg.BodyFormat = System.Web.Mail.MailFormat.Html;
                //邮件正文
                mmsg.Body = model.Content;
                //正文编码
                mmsg.BodyEncoding = Encoding.UTF8;
                //优先级
                mmsg.Priority = System.Web.Mail.MailPriority.High;

                System.Web.Mail.MailAttachment data = null;
                if (model.AttachFilePath != "")
                {
                    System.Web.Mail.MailAttachment attachment = new System.Web.Mail.MailAttachment(model.AttachFilePath); //create the attachment
                    mmsg.Attachments.Add(attachment); //add the attachment
                }
                //发件者邮箱地址
                mmsg.From = model.SenderAddress;

                //收件人收箱地址
                mmsg.To = model.ReceiverAddress;
                mmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
                //用户名
                mmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", model.SenderAddress);
                //密码
                mmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", model.SenderPassword);
                //端口
                mmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465");
                //使用SSL
                mmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
                //Smtp服务器
                System.Web.Mail.SmtpMail.SmtpServer = "smtp.qq.com";
                System.Web.Mail.SmtpMail.Send(mmsg);
                return true;
            }
            catch (Exception e)
            {
                FLog.WriteLog("发送邮件失败,异常信息:" e.Message);
                return false;
            }
        }

2.Quartz.Net原来是不间断运行判断时间点,但发现可能导致时间精度不够,换成CronSchedule的日历表达式方式

3.使用c#的Process执行cmd命令,默认异步执行,我们需要加入完成事件,在完成事件后执行发送邮件操作

0 人点赞