1 public static class Email 2 { 3 /// <summary> 4 /// 發件人 5 /// </summary> 6 public static string mailFrom { get; set; } 7 8 /// <summary> 9 /// 收件人 10 /// </summary> 11 public static string[] mailToArray { get; set; } 12 13 /// <summary> 14 /// 抄送 15 /// </summary> 16 public static string[] mailCcArray { get; set; } 17 18 /// <summary> 19 /// 標題 20 /// </summary> 21 public static string mailSubject { get; set; } 22 23 /// <summary> 24 /// 正文 25 /// </summary> 26 public static string mailBody { get; set; } 27 28 /// <summary> 29 /// 發件人密碼 30 /// </summary> 31 public static string mailPwd { get; set; } 32 33 /// <summary> 34 /// SMTP郵件伺服器 35 /// </summary> 36 public static string host { get; set; } 37 38 /// <summary> 39 /// 郵件伺服器埠 40 /// </summary> 41 public static int port { get; set; } 42 43 /// <summary> 44 /// 正文是否是html格式 45 /// </summary> 46 public static bool isbodyHtml { get; set; } 47 48 /// <summary> 49 /// 附件 50 /// </summary> 51 public static string[] attachmentsPath { get; set; } 52 53 public static bool Send() 54 { 55 //使用指定的郵件地址初始化MailAddress實例 56 MailAddress maddr = new MailAddress(mailFrom); 57 58 //初始化MailMessage實例 59 MailMessage myMail = new MailMessage(); 60 61 //向收件人地址集合添加郵件地址 62 if (mailToArray != null) 63 { 64 for (int i = 0; i < mailToArray.Length; i++) 65 { 66 myMail.To.Add(mailToArray[i].ToString()); 67 } 68 } 69 70 //向抄送收件人地址集合添加郵件地址 71 if (mailCcArray != null) 72 { 73 for (int i = 0; i < mailCcArray.Length; i++) 74 { 75 myMail.CC.Add(mailCcArray[i].ToString()); 76 } 77 } 78 //發件人地址 79 myMail.From = maddr; 80 81 //電子郵件的標題 82 myMail.Subject = mailSubject; 83 84 //電子郵件的主題內容使用的編碼 85 myMail.SubjectEncoding = Encoding.UTF8; 86 87 //電子郵件正文 88 myMail.Body = mailBody; 89 90 //電子郵件正文的編碼 91 myMail.BodyEncoding = Encoding.Default; 92 93 //電子郵件優先順序 94 myMail.Priority = MailPriority.High; 95 96 //電子郵件不是html格式 97 myMail.IsBodyHtml = isbodyHtml; 98 99 //在有附件的情況下添加附件 100 try 101 { 102 if (attachmentsPath != null && attachmentsPath.Length > 0) 103 { 104 Attachment attachFile = null; 105 foreach (string path in attachmentsPath) 106 { 107 attachFile = new Attachment(path); 108 myMail.Attachments.Add(attachFile); 109 } 110 } 111 } 112 catch (Exception err) 113 { 114 throw new Exception("在添加附件時有錯誤:" + err.Message); 115 } 116 117 SmtpClient client = new SmtpClient(); 118 119 //指定發件人的郵件地址和密碼以驗證發件人身份 120 client.Credentials = new NetworkCredential(mailFrom, mailPwd); 121 122 //設置SMTP郵件伺服器 123 //client.Host = "smtp." + myMail.From.Host; 124 client.Host = host; 125 126 //SMTP郵件伺服器埠 127 client.Port = port; 128 129 //是否使用安全連接 130 //client.EnableSsl = true; 131 132 try 133 { 134 //將郵件發送到SMTP郵件伺服器 135 client.Send(myMail); 136 return true; 137 } 138 catch (SmtpException ex) 139 { 140 string msg = ex.Message; 141 return false; 142 } 143 144 }