MailUtil.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using MailKit.Net.Smtp;
  8. using MimeKit;
  9. namespace wispro.sp.utility
  10. {
  11. public class MailUtil
  12. {
  13. public static void SendEmail(string subject, string body,string toMailName, string toEmail,string AttachFiles=null)
  14. {
  15. MimeMessage message = new MimeMessage();
  16. string strMail = ConfigHelper.GetSectionValue("MailSetting:mail");
  17. MailboxAddress from = new MailboxAddress("绩效系统",strMail);
  18. message.From.Add(from);
  19. MailboxAddress to = new MailboxAddress(toMailName, toEmail);
  20. message.To.Add(to);
  21. message.Subject = subject;
  22. BodyBuilder bodyBuilder = new BodyBuilder();
  23. bodyBuilder.HtmlBody = body;
  24. if (!string.IsNullOrEmpty(AttachFiles))
  25. {
  26. var files = AttachFiles.Split(';');
  27. foreach(var file in files)
  28. {
  29. if (!string.IsNullOrEmpty(file.Trim()))
  30. {
  31. if (System.IO.File.Exists(file))
  32. {
  33. bodyBuilder.Attachments.Add(file);
  34. }
  35. }
  36. }
  37. }
  38. message.Body = bodyBuilder.ToMessageBody();
  39. SmtpClient client = new SmtpClient();
  40. var strServer = ConfigHelper.GetSectionValue("MailSetting:Server");
  41. var strPort = ConfigHelper.GetSectionValue("MailSetting:Port");
  42. var strAccount = ConfigHelper.GetSectionValue("MailSetting:Account");
  43. var strPassword = ConfigHelper.GetSectionValue("MailSetting:Password");
  44. client.Connect(strServer , int.Parse(strPort),true); //例如:smtp.exmail.qq.com,465
  45. client.Authenticate(strAccount, strPassword); //发送邮件的账户密码
  46. client.Send(message);
  47. client.Disconnect(true);
  48. client.Dispose();
  49. }
  50. private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
  51. {
  52. if(e.Error != null){
  53. System.Diagnostics.Debug.WriteLine(e.Error.ToString());
  54. }
  55. }
  56. }
  57. }