/// <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; }
工作中用到的一個郵件發送代碼,帶附件,附件發送完成後,可以刪除。