MailAddress.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. namespace System.Web.Mail {
  3. internal class MailAddress {
  4. protected string user;
  5. protected string host;
  6. protected string name;
  7. public string User {
  8. get { return user; }
  9. set { user = value; }
  10. }
  11. public string Host {
  12. get { return host; }
  13. set { host = value; }
  14. }
  15. public string Name {
  16. get { return name; }
  17. set { name = value; }
  18. }
  19. public string Address {
  20. get { return String.Format( "{0}@{1}" , user , host ); }
  21. set {
  22. string[] parts = value.Split( new char[] { '@' } );
  23. if( parts.Length != 2 )
  24. throw new FormatException( "Email address is incorrect: " + value );
  25. user = parts[ 0 ];
  26. host = parts[ 1 ];
  27. }
  28. }
  29. public static MailAddress Parse( string str ) {
  30. MailAddress addr = new MailAddress();
  31. string address = null;
  32. string nameString = null;
  33. string[] parts = str.Split( new char[] { ' ' } );
  34. // find the address: [email protected]
  35. // and put to gether all the parts
  36. // before the address as nameString
  37. foreach( string part in parts ) {
  38. if( part.IndexOf( '@' ) > 0 ) {
  39. address = part;
  40. break;
  41. }
  42. nameString = nameString + part + " ";
  43. }
  44. if( address == null )
  45. throw new FormatException( "Email address not found in: " + str );
  46. address = address.Trim( new char[] { '<' , '>' , '(' , ')' } );
  47. addr.Address = address;
  48. if( nameString != null ) {
  49. addr.Name = nameString.Trim();
  50. addr.Name = ( addr.Name.Length == 0 ? null : addr.Name );
  51. }
  52. return addr;
  53. }
  54. public override string ToString() {
  55. string retString = "";
  56. if( name == null ) {
  57. retString = String.Format( "<{0}>" , this.Address );
  58. } else {
  59. retString = String.Format( "\"{0}\" <{1}>" , this.Name , this.Address);
  60. }
  61. return retString;
  62. }
  63. }
  64. }