/// <summary> /// 发送邮件方法 /// </summary> /// <param name="sendMail">发送人</param> /// <param name="recMail">接收人(可以是多个,用;分号隔开)</param> /// <param name="subject">主题</param> /// <param name="body">正文</param> /// <param name="host">服务器名称</param> /// <param name="pwd">密码</param> /// <param name="filePath">文件路径</param> /// <returns></returns> public static bool SendMail(string sendMail,string recMail,string subject,string body,string host,string pwd,string filePath) { bool result = true; MailMessage mailObj = new MailMessage(); try { mailObj.From = new MailAddress(sendMail); //发送人邮箱地址 string[] rmail = recMail.Split(‘;‘); foreach (var item in rmail) { mailObj.To.Add(item); //收件人邮箱地址 } mailObj.Subject = subject; //主题 mailObj.Body = body; //正文 mailObj.IsBodyHtml = true; if (!string.IsNullOrWhiteSpace(filePath)) { mailObj.Attachments.Add(new Attachment(@filePath, System.Net.Mime.MediaTypeNames.Application.Rtf)); } SmtpClient smtp = new SmtpClient(); smtp.Host = host; //smtp服务器名称 smtp.Port = 25; smtp.UseDefaultCredentials = true; smtp.Credentials = new NetworkCredential(sendMail, pwd); //发送人的登录名和密码 smtp.Send(mailObj); } catch (Exception ex) { result = false; CommOperation.EditFileLog("SendMail.txt", ex.Message, false); } finally { //释放邮件发送点用附件--没有这句,会无法删除,一直占用文件。 foreach (Attachment item in mailObj.Attachments) { item.Dispose(); } } return result; }工作中用到的一个邮件发送代码,带附件,附件发送完成后,可以删除。
时间: 2024-09-30 07:39:18