2
0

MailAddress.cs 1.9 KB

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