C#通过拼接协议的方式来发送邮件类库
1 using System; 2 using System.Collections.Generic; 3 using System.Net; 4 using System.Net.Mail; 5 using System.Net.Sockets; 6 using System.Text; 7 8 namespace HR.Common 9 { 10 #region SMTP Client 11 public class SMTPClient : TcpClient 12 { 13 /// <summary> 14 /// 是否链接 15 /// </summary> 16 /// <returns></returns> 17 public bool isConnected() 18 { 19 return Active; 20 } 21 22 /// <summary> 23 /// 向服务器发送指令 24 /// </summary> 25 /// <param name="Command">指令内容</param> 26 public void SendCommandToServer(string Command) 27 { 28 NetworkStream ns = this.GetStream(); 29 byte[] WriteBuffer = null; 30 WriteBuffer = new byte[Command.Length]; 31 WriteBuffer = Encoding.Default.GetBytes(Command); 32 ns.Write(WriteBuffer, 0, WriteBuffer.Length); 33 return; 34 } 35 36 /// <summary> 37 /// 返回服务器处理结果 38 /// </summary> 39 /// <returns></returns> 40 public string GetServerResponse() 41 { 42 int StreamSize; 43 string ReturnValue = ""; 44 byte[] ReadBuffer; 45 NetworkStream ns = this.GetStream(); 46 47 ReadBuffer = new byte[1024]; 48 StreamSize = ns.Read(ReadBuffer, 0, ReadBuffer.Length); 49 if (StreamSize == 0) 50 { 51 return ReturnValue; 52 } 53 else 54 { 55 ReturnValue = Encoding.Default.GetString(ReadBuffer); 56 return ReturnValue; 57 } 58 } 59 60 /// <summary> 61 /// 生成SMTPCode 62 /// </summary> 63 /// <param name="s">信息内容</param> 64 /// <param name="SMTPCode">SMTPCode</param> 65 /// <returns></returns> 66 public bool DoesStringContainSMTPCode(string s, string SMTPCode) 67 { 68 return (s.IndexOf(SMTPCode, 0, 10) == -1) ? false : true; 69 } 70 71 } 72 #endregion 73 74 #region SckMail 75 public class SckMail 76 { 77 /// <summary> 78 /// 邮件发送优先级权举表 79 /// </summary> 80 public enum Prioritys 81 { 82 /// <summary> 83 /// 最高级别 84 /// </summary> 85 HIGH = 1, 86 /// <summary> 87 /// 默认级别 88 /// </summary> 89 NORMAL = 3, 90 /// <summary> 91 /// 最低级别 92 /// </summary> 93 LOW = 5 94 } 95 96 /// <summary> 97 /// 构造函数 98 /// </summary> 99 public SckMail() 100 { 101 strErrMessage = ""; 102 strResponse = ""; 103 } 104 105 #region "返回信息" 106 107 /// <summary> 108 /// SMTP服务器反馈的信息 109 /// </summary> 110 private string strResponse = ""; 111 112 /// <summary> 113 /// 取得SMTP服务器反馈的信息 114 /// </summary> 115 public string ServerResponse 116 { 117 get 118 { 119 return strResponse; 120 } 121 } 122 123 /// <summary> 124 /// 错误反馈信息 125 /// </summary> 126 private string strErrMessage = ""; 127 128 /// <summary> 129 /// 取得错误反馈信息 130 /// </summary> 131 public string ErrorMessage 132 { 133 get 134 { 135 return strErrMessage; 136 } 137 } 138 139 /// <summary> 140 /// 认证用户名 141 /// </summary> 142 private string strUsername = ""; 143 144 /// <summary> 145 /// 认证用户名 146 /// </summary> 147 public string Username 148 { 149 get { return strUsername; } 150 set { strUsername = value; } 151 } 152 153 /// <summary> 154 /// 认证密码 155 /// </summary> 156 private string strPassword = ""; 157 158 /// <summary> 159 /// 认证密码 160 /// </summary> 161 public string Password 162 { 163 get { return strPassword; } 164 set { strPassword = value; } 165 } 166 167 #endregion 168 169 #region "邮件属性" 170 171 /// <summary> 172 /// SMTP 邮件服务器 173 /// </summary> 174 private string _SmtpHost = ""; 175 176 /// <summary> 177 /// SMTP 邮件服务器 178 /// </summary> 179 public string SmtpHost 180 { 181 get 182 { 183 return _SmtpHost; 184 } 185 set 186 { 187 _SmtpHost = value; 188 } 189 } 190 191 /// <summary> 192 /// SMTP邮件服务器端口 193 /// </summary> 194 private int _Port = 25; 195 196 /// <summary> 197 /// SMTP邮件服务器端口 198 /// </summary> 199 public int Port 200 { 201 get 202 { 203 return _Port; 204 } 205 set 206 { 207 _Port = value; 208 } 209 } 210 211 #endregion 212 213 /// <summary> 214 /// Base64加密 215 /// </summary> 216 /// <param name="code">明文</param> 217 /// <returns>密文</returns> 218 public string MailBase64(string code) 219 { 220 string encode = ""; 221 try 222 { 223 byte[] bytes = Encoding.GetEncoding(Encoding.Default.CodePage).GetBytes(code); 224 encode = Convert.ToBase64String(bytes); 225 } 226 catch (Exception ex) 227 { 228 //utils.LastError = ex; 229 encode = code; 230 } 231 return encode; 232 } 233 234 /// <summary> 235 /// Socket发送邮件 236 /// </summary> 237 /// <param name="strFrom">发送人 邮件地址</param> 238 /// <param name="strDisplayFromName">发送人显示名</param> 239 /// <param name="strTo">收件人 邮件地址</param> 240 /// <param name="strDisplayToName">收件人显示名</param> 241 /// <param name="clsPriority">邮件优先级</param> 242 /// <param name="blnHtml">是否发送HTML邮件</param> 243 /// <param name="strBase">发送来源(可以为空)</param> 244 /// <param name="strMessage">发送内容</param> 245 /// <param name="strSubject">邮件主题</param> 246 public void SendMail(string strFrom, string strDisplayFromName, string strTo, string strDisplayToName, 247 Prioritys clsPriority, bool blnHtml, string strBase, string strSubject, string strMessage) 248 { 249 string strResponseNumber = ""; 250 bool bolConnect = false; 251 List<string> strSendBuffer = null; 252 string[] strResponseCode = { "220", "235", "250", "251", "354", "334", "221" }; // success codes from SMTP server 253 254 try 255 { 256 strSendBuffer = new List<string>(); 257 258 SMTPClient smtpcMail = new SMTPClient(); 259 260 smtpcMail.Connect(_SmtpHost, _Port); 261 bolConnect = smtpcMail.isConnected(); 262 263 //判断是否进行了连接 264 if (!bolConnect) 265 { 266 strErrMessage = "Smtp服务器连接失败..."; 267 return; 268 } 269 270 //读取反馈信息 271 strResponseNumber = smtpcMail.GetServerResponse(); 272 if (smtpcMail.DoesStringContainSMTPCode(strResponseNumber, "220")) 273 { 274 this.strResponse += strResponseNumber; 275 } 276 else 277 { 278 this.strErrMessage = "连接失败:" + strResponseNumber; 279 return; 280 } 281 282 string strData = ""; 283 strData = string.Concat("HELO ", _SmtpHost); 284 strData = string.Concat(strData, "\r\n"); 285 strSendBuffer.Add(strData); 286 287 strData = ""; 288 strData = string.Concat(strData, "AUTH LOGIN"); 289 strData = string.Concat(strData, "\r\n"); 290 strSendBuffer.Add(strData); 291 292 strData = ""; 293 strData = string.Concat(strData, MailBase64(this.strUsername)); 294 strData = string.Concat(strData, "\r\n"); 295 strSendBuffer.Add(strData); 296 297 strData = ""; 298 strData = string.Concat(strData, MailBase64(this.strPassword)); 299 strData = string.Concat(strData, "\r\n"); 300 strSendBuffer.Add(strData); 301 302 strData = ""; 303 strData = string.Concat("MAIL FROM: ", "<" + strFrom + ">"); 304 strData = string.Concat(strData, "\r\n"); 305 strSendBuffer.Add(strData); 306 307 strData = ""; 308 strData = string.Concat("RCPT TO: ", "<" + strTo + ">"); 309 strData = string.Concat(strData, "\r\n"); 310 strSendBuffer.Add(strData); 311 312 strData = ""; 313 strData = string.Concat("DATA", "\r\n"); 314 strSendBuffer.Add(strData); 315 316 strData = ""; 317 strData = string.Concat("From: ", strDisplayFromName + "<" + strFrom + ">"); 318 strData = string.Concat(strData, "\r\n"); 319 strData = string.Concat(strData, "To: "); 320 strData = string.Concat(strData, strDisplayToName + "<" + strTo + ">"); 321 strData = string.Concat(strData, "\r\n"); 322 strData = string.Concat(strData, "Subject: "); 323 strData = string.Concat(strData, strSubject); 324 strData = string.Concat(strData, "\r\n"); 325 strData = string.Concat(strData, "MIME-Version: 1.0"); 326 strData = string.Concat(strData, "\r\n"); 327 strData = string.Concat(strData, "X-Priority: " + clsPriority); 328 strData = string.Concat(strData, "\r\n"); 329 strData = string.Concat(strData, "X-MSMail-Priority: " + clsPriority); 330 strData = string.Concat(strData, "\r\n"); 331 if (blnHtml == true) 332 { 333 strData = string.Concat(strData, "Content-Type: text/html;"); 334 } 335 else 336 { 337 strData = string.Concat(strData, "Content-Type: text/plain;"); 338 } 339 strData = string.Concat(strData, "\r\n"); 340 strData = string.Concat(strData, "charset=\"iso-8859-1\""); 341 strData = string.Concat(strData, "\r\n"); 342 strData = string.Concat(strData, "Content-Transfer-Encoding: base64"); 343 strData = string.Concat(strData, "\r\n"); 344 strData = string.Concat(strData, "Content-Base: \"" + strBase + "\""); 345 strData = string.Concat(strData, "\r\n" + "\r\n"); 346 347 strData = string.Concat(strData, MailBase64(strMessage)); 348 strData = string.Concat(strData, "\r\n.\r\n"); 349 strSendBuffer.Add(strData); 350 351 strData = ""; 352 strData = string.Concat(strData, "QUIT\r\n"); 353 strSendBuffer.Add(strData); 354 int i = 0; 355 356 while (i < strSendBuffer.Count) 357 { 358 smtpcMail.SendCommandToServer(strSendBuffer[i]); 359 strResponseNumber = smtpcMail.GetServerResponse(); 360 361 for (int j = 0; j < strResponseCode.Length; j++) 362 { 363 if (smtpcMail.DoesStringContainSMTPCode(strResponseNumber, strResponseCode[j])) 364 { 365 this.strResponse += strResponseNumber; 366 this.strResponse += "<br>"; 367 break; 368 } 369 else 370 { 371 if (j == strResponseCode.Length - 1) 372 { 373 this.strErrMessage += strResponseNumber; 374 this.strErrMessage += strSendBuffer[i]; 375 return; 376 } 377 } 378 } 379 380 i++; 381 } // 结束循环 382 } 383 catch (SocketException err) 384 { 385 this.strErrMessage += err.Message + " " + err.StackTrace; 386 throw (err); 387 } 388 catch (Exception e) 389 { 390 this.strErrMessage += e.Message + " " + e.StackTrace; 391 throw (e); 392 } 393 } 394 395 } 396 #endregion 397 398 #region SMTPMail 399 public class SMTPMail 400 { 401 private string smtpServer; 402 private string smtpUser; 403 private string smtpPwd; 404 private string userEmail; 405 private string subject; 406 private string body; 407 408 private int serverPort = 25; //默认为25 409 private bool isHtml = false; // 是否Html邮件 410 411 //private string charset = "GB2312"; //设定语言代码,默认设定为GB2312,如不需要可设置为"" 412 //private string priority = "Normal"; //邮件发送优先级,可设置为"High","Normal","Low" 413 414 /// <summary> 415 /// 邮件服务器地址 416 /// </summary> 417 public string SmtpServer 418 { 419 get { return smtpServer; } 420 set { smtpServer = value; } 421 } 422 423 /// <summary> 424 /// 邮件服务器端口号 425 /// </summary> 426 public int ServerPort 427 { 428 get { return serverPort; } 429 set { serverPort = value; } 430 } 431 432 /// <summary> 433 /// 是否Html邮件 434 /// </summary> 435 public bool IsHtml 436 { 437 get { return isHtml; } 438 set { isHtml = value; } 439 } 440 441 ///// <summary> 442 ///// 代码 443 ///// </summary> 444 //public string Charset 445 //{ 446 // get { return charset; } 447 // set { charset = value; } 448 //} 449 ///// <summary> 450 ///// 邮件发送优先级,可设置为"High","Normal","Low"或"1","3","5" 451 ///// </summary> 452 //public string Priority 453 //{ 454 // set 455 // { 456 // switch (value.ToLower()) 457 // { 458 // case "high": 459 // priority = "High"; 460 // break; 461 462 // case "1": 463 // priority = "High"; 464 // break; 465 466 // case "normal": 467 // priority = "Normal"; 468 // break; 469 470 // case "3": 471 // priority = "Normal"; 472 // break; 473 474 // case "low": 475 // priority = "Low"; 476 // break; 477 478 // case "5": 479 // priority = "Low"; 480 // break; 481 482 // default: 483 // priority = "High"; 484 // break; 485 // } 486 // } 487 //} 488 489 490 491 /// <summary> 492 /// 邮件发送帐号 493 /// </summary> 494 495 public string SmtpUser 496 { 497 get { return smtpUser; } 498 set { smtpUser = value; } 499 } 500 501 /// <summary> 502 /// 邮件发送帐号密码 503 /// </summary> 504 public string SmtpPwd 505 { 506 get { return smtpPwd; } 507 set { smtpPwd = value; } 508 } 509 510 /// <summary> 511 /// 用户邮件地址,即是被发送人的邮件地址 512 /// </summary> 513 public string UserEmail 514 { 515 get { return userEmail; } 516 set { userEmail = value; } 517 } 518 519 /// <summary> 520 /// 邮件标题 521 /// </summary> 522 public string Subject 523 { 524 get { return subject; } 525 set { subject = value; } 526 } 527 528 /// <summary> 529 /// 邮件主体 530 /// </summary> 531 public string Body 532 { 533 get { return body; } 534 set { body = value; } 535 } 536 537 /// <summary> 538 /// 发送邮件 539 /// </summary> 540 /// <returns>bool</returns> 541 public bool SendEmail() 542 { 543 try 544 { 545 using (MailMessage mailMsg = new MailMessage(this.smtpUser, this.userEmail)) 546 { 547 mailMsg.Subject = this.subject; 548 mailMsg.Body = this.body; 549 mailMsg.SubjectEncoding = Encoding.UTF8; 550 551 mailMsg.BodyEncoding = Encoding.UTF8; 552 mailMsg.IsBodyHtml = this.isHtml; 553 mailMsg.Priority = MailPriority.Normal; 554 555 SmtpClient smtpClient = new SmtpClient(this.smtpServer); 556 smtpClient.Port = this.serverPort; 557 smtpClient.UseDefaultCredentials = false; 558 smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; 559 smtpClient.Credentials = new NetworkCredential(this.smtpUser, this.smtpPwd); 560 smtpClient.Send(mailMsg); 561 562 563 return true; 564 } 565 566 } 567 catch (Exception ex) 568 { 569 570 throw ex; 571 } 572 } 573 } 574 #endregion 575 576 #region MailInfo 577 public class MailInfo 578 { 579 /// <summary> 580 /// 邮件服务器地址 581 /// </summary> 582 public string SmtpHost = string.Empty; 583 584 /// <summary> 585 /// 端口号 586 /// </summary> 587 public int Port = 25; 588 589 /// <summary> 590 /// 邮箱登录名 591 /// </summary> 592 public string UserName = string.Empty; 593 594 /// <summary> 595 /// 邮箱登录密码 596 /// </summary> 597 public string Password = string.Empty; 598 599 /// <summary> 600 /// 发送人邮件 601 /// </summary> 602 public string From = string.Empty; 603 604 /// <summary> 605 /// 发送人姓名 606 /// </summary> 607 public string FromName = string.Empty; 608 /// <summary> 609 /// 获取邮件配置信息 610 /// </summary> 611 /// <returns></returns> 612 public MailInfo GetMailInfo() 613 { 614 var config = System.Web.Configuration.WebConfigurationManager.AppSettings; 615 MailInfo model = new MailInfo(); 616 model.SmtpHost = config["SmtpHost"].Trim(); 617 try 618 { 619 if (!int.TryParse(config["SmtpPort"], out model.Port)) 620 { 621 model.Port = 25; 622 } 623 } 624 catch 625 { 626 model.Port = 25; 627 } 628 model.UserName = config["EmailUserName"]; 629 model.Password = config["EmailPassword"]; 630 model.From = config["EmailFrom"]; 631 model.FromName = config["EmailFromName"]; 632 return model; 633 } 634 public static string SendMail(string email, string title, string content) 635 { 636 // bool IsSuccess = true; 637 string mailContent = string.Empty; 638 string mailinfo = string.Empty; 639 SckMail mail = null; 640 MailInfo mi =new MailInfo(); 641 try 642 { 643 mail = new SckMail(); 644 mi = mi.GetMailInfo(); 645 mail.SmtpHost = mi.SmtpHost; 646 mail.Port = mi.Port; 647 mail.Username = mi.From; 648 mail.Password = mi.Password; 649 mailContent = content; 650 mail.SendMail 651 ( 652 mi.From, 653 mi.FromName, 654 email, 655 email, 656 SckMail.Prioritys.NORMAL, 657 true, 658 "", 659 CheckStr(title), 660 mailContent 661 ); 662 if (mail.ErrorMessage != "") 663 { 664 mailinfo = mail.ErrorMessage; 665 } 666 } 667 catch (Exception e) 668 { 669 mailinfo = e.Message; 670 } 671 finally 672 { 673 mail = null; 674 } 675 return mailinfo; 676 } 677 public static string CheckStr(object str) 678 { 679 string ret = ""; 680 try 681 { 682 if (str == null) ret = ""; 683 else 684 { 685 ret = str.ToString(); 686 ret = ret.Replace("'", "''"); 687 } 688 } 689 catch 690 { 691 ret = ""; 692 } 693 return ret; 694 } 695 } 696 #endregion 697 }
西安.NET俱乐部群