200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > MYSQL自动备份并发送邮件工具

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

时间:2022-10-02 04:04:00

相关推荐

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

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

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

1.MYSQL自动备份

2.发送邮件

3.定时任务

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

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

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服务商域名,和你的邮箱账号,发送邮件授权码。

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);//收件人//.Add(sender);//抄送人message.Subject = model.Title;//标题message.Body = model.Content;//内容message.IsBodyHtml = true;//是否支持内容为HTMLif (!string.IsNullOrEmpty(model.AttachFilePath)){//将文件进行转换成AttachmentsAttachment 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 = "";//client.Port = 465;client.EnableSsl = true;//是否启用SSLclient.Timeout = 10000;//超时client.DeliveryMethod = work;client.UseDefaultCredentials = false;client.Credentials = new NetworkCredential(model.SenderAddress, model.SenderPassword);client.Send(message);return true;}catch (Exception e){return false;}}

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

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自动定时备份并发送数据备份文件至指定邮箱

更新1220 修复问题

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

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 attachmentmmsg.Attachments.Add(attachment); //add the attachment}//发件者邮箱地址mmsg.From = model.SenderAddress;//收件人收箱地址mmsg.To = model.ReceiverAddress;mmsg.Fields.Add("/cdo/configuration/smtpauthenticate", "1");//用户名mmsg.Fields.Add("/cdo/configuration/sendusername", model.SenderAddress);//密码mmsg.Fields.Add("/cdo/configuration/sendpassword", model.SenderPassword);//端口mmsg.Fields.Add("/cdo/configuration/smtpserverport", "465");//使用SSLmmsg.Fields.Add("/cdo/configuration/smtpusessl", "true");//Smtp服务器System.Web.Mail.SmtpMail.SmtpServer = "";System.Web.Mail.SmtpMail.Send(mmsg);return true;}catch (Exception e){FLog.WriteLog("发送邮件失败,异常信息:"+e.Message);return false;}}

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

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。