Code:
/ 4.0 / 4.0 / DEVDIV_TFS / Dev10 / Releases / RTMRel / ndp / fx / src / Net / System / Net / Mail / MailAddress.cs / 1305376 / MailAddress.cs
//------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//-----------------------------------------------------------------------------
namespace System.Net.Mail
{
using System;
using System.Text;
using System.Net.Mime;
using System.Diagnostics;
using System.Globalization;
//
// This class stores the basic components of an e-mail address as described in RFC 2822 Section 3.4.
// Any parsing required is done with the MailAddressParser class.
//
public class MailAddress
{
// These components form an e-mail address when assembled as follows:
// "EncodedDisplayname"
private readonly Encoding displayNameEncoding;
private readonly string displayName;
private readonly string userName;
private readonly string host;
// For internal use only by MailAddressParser.
// The components were already validated before this is called.
internal MailAddress(string displayName, string userName, string domain) {
this.host = domain;
this.userName = userName;
this.displayName = displayName;
this.displayNameEncoding = Encoding.GetEncoding(MimeBasePart.defaultCharSet);
Debug.Assert(host != null,
"host was null in internal constructor");
Debug.Assert(userName != null,
"userName was null in internal constructor");
Debug.Assert(displayName != null,
"displayName was null in internal constructor");
}
public MailAddress(string address) : this(address, null, (Encoding)null) {
}
public MailAddress(string address, string displayName) : this(address, displayName, (Encoding)null) {
}
//
// This constructor validates and stores the components of an e-mail address.
//
// Preconditions:
// - 'address' must not be null or empty.
//
// Postconditions:
// - The e-mail address components from the given 'address' are parsed, which should be formatted as:
// "EncodedDisplayname"
// - If a 'displayName' is provided separately, it overrides whatever display name is parsed from the 'address'
// field. The display name does not need to be pre-encoded if a 'displayNameEncoding' is provided.
//
// A FormatException will be thrown if any of the components in 'address' are invalid.
public MailAddress(string address, string displayName, Encoding displayNameEncoding) {
if (address == null){
throw new ArgumentNullException("address");
}
if (address == String.Empty){
throw new ArgumentException(SR.GetString(SR.net_emptystringcall,"address"), "address");
}
this.displayNameEncoding = displayNameEncoding ?? Encoding.GetEncoding(MimeBasePart.defaultCharSet);
this.displayName = displayName ?? string.Empty;
// Check for bounding quotes
if (!String.IsNullOrEmpty(this.displayName)) {
if (this.displayName.Length >= 2 && this.displayName[0] == '\"'
&& this.displayName[this.displayName.Length - 1] == '\"') {
// Peal bounding quotes, they'll get re-added later.
this.displayName = this.displayName.Substring(1, this.displayName.Length - 2);
}
}
MailAddress result = MailAddressParser.ParseAddress(address);
this.host = result.host;
this.userName = result.userName;
// If we were not given a display name, use the one parsed from 'address'.
if (String.IsNullOrEmpty(this.displayName)) {
this.displayName = result.displayName;
}
}
public string DisplayName
{
get
{
return displayName;
}
}
public string User
{
get
{
return this.userName;
}
}
public string Host
{
get
{
return this.host;
}
}
public string Address
{
get
{
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", userName, host);
}
}
internal string SmtpAddress{
get{
return String.Format(CultureInfo.InvariantCulture, "<{0}>", Address);
}
}
///
/// this returns the full address with quoted display name.
/// i.e. "some email address display name"
/// if displayname is not provided then this returns only user@host (no angle brackets)
///
///
public override string ToString() {
if (String.IsNullOrEmpty(DisplayName)) {
return this.Address;
}
else {
return String.Format("\"{0}\" {1}", DisplayName, SmtpAddress);
}
}
public override bool Equals(object value) {
if (value == null) {
return false;
}
return ToString().Equals(value.ToString(),StringComparison.InvariantCultureIgnoreCase);
}
public override int GetHashCode(){
return ToString().GetHashCode();
}
static EncodedStreamFactory encoderFactory = new EncodedStreamFactory();
// Encodes the full email address, folding as needed
internal string Encode(int charsConsumed)
{
string encodedAddress = String.Empty;
IEncodableStream encoder;
byte[] buffer;
Debug.Assert(this.Address != null, "address was null");
//do we need to take into account the Display name? If so, encode it
if (!String.IsNullOrEmpty(this.displayName))
{
//figure out the encoding type. If it's all ASCII and contains no CRLF then
//it does not need to be encoded for parity with other email clients. We will
//however fold at the end of the display name so that the email address itself can
//be appended.
if (MimeBasePart.IsAscii(this.displayName, false))
{
encodedAddress = String.Format("\"{0}\"", this.displayName);
}
else
{
//encode the displayname since it's non-ascii
encoder = encoderFactory.GetEncoderForHeader(this.displayNameEncoding, false, charsConsumed);
buffer = displayNameEncoding.GetBytes(this.displayName);
encoder.EncodeBytes(buffer, 0, buffer.Length);
encodedAddress = encoder.GetEncodedString();
}
//the extra space is because there should be a non-printable whitespace char
//following the fold (CRLF) and there is supposed to be a space between the display name and
//the address so this is necessary.
encodedAddress += "\r\n ";
}
//now we have the encoded display name (if present), we need to append the address to it.
if (!String.IsNullOrEmpty(encodedAddress))
{
//address should be enclosed in <> when a display name is present
encodedAddress += SmtpAddress;
}
else
{
//no display name, just return the address
encodedAddress = this.Address;
}
return encodedAddress;
}
}
}
// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
//------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//-----------------------------------------------------------------------------
namespace System.Net.Mail
{
using System;
using System.Text;
using System.Net.Mime;
using System.Diagnostics;
using System.Globalization;
//
// This class stores the basic components of an e-mail address as described in RFC 2822 Section 3.4.
// Any parsing required is done with the MailAddressParser class.
//
public class MailAddress
{
// These components form an e-mail address when assembled as follows:
// "EncodedDisplayname"
private readonly Encoding displayNameEncoding;
private readonly string displayName;
private readonly string userName;
private readonly string host;
// For internal use only by MailAddressParser.
// The components were already validated before this is called.
internal MailAddress(string displayName, string userName, string domain) {
this.host = domain;
this.userName = userName;
this.displayName = displayName;
this.displayNameEncoding = Encoding.GetEncoding(MimeBasePart.defaultCharSet);
Debug.Assert(host != null,
"host was null in internal constructor");
Debug.Assert(userName != null,
"userName was null in internal constructor");
Debug.Assert(displayName != null,
"displayName was null in internal constructor");
}
public MailAddress(string address) : this(address, null, (Encoding)null) {
}
public MailAddress(string address, string displayName) : this(address, displayName, (Encoding)null) {
}
//
// This constructor validates and stores the components of an e-mail address.
//
// Preconditions:
// - 'address' must not be null or empty.
//
// Postconditions:
// - The e-mail address components from the given 'address' are parsed, which should be formatted as:
// "EncodedDisplayname"
// - If a 'displayName' is provided separately, it overrides whatever display name is parsed from the 'address'
// field. The display name does not need to be pre-encoded if a 'displayNameEncoding' is provided.
//
// A FormatException will be thrown if any of the components in 'address' are invalid.
public MailAddress(string address, string displayName, Encoding displayNameEncoding) {
if (address == null){
throw new ArgumentNullException("address");
}
if (address == String.Empty){
throw new ArgumentException(SR.GetString(SR.net_emptystringcall,"address"), "address");
}
this.displayNameEncoding = displayNameEncoding ?? Encoding.GetEncoding(MimeBasePart.defaultCharSet);
this.displayName = displayName ?? string.Empty;
// Check for bounding quotes
if (!String.IsNullOrEmpty(this.displayName)) {
if (this.displayName.Length >= 2 && this.displayName[0] == '\"'
&& this.displayName[this.displayName.Length - 1] == '\"') {
// Peal bounding quotes, they'll get re-added later.
this.displayName = this.displayName.Substring(1, this.displayName.Length - 2);
}
}
MailAddress result = MailAddressParser.ParseAddress(address);
this.host = result.host;
this.userName = result.userName;
// If we were not given a display name, use the one parsed from 'address'.
if (String.IsNullOrEmpty(this.displayName)) {
this.displayName = result.displayName;
}
}
public string DisplayName
{
get
{
return displayName;
}
}
public string User
{
get
{
return this.userName;
}
}
public string Host
{
get
{
return this.host;
}
}
public string Address
{
get
{
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", userName, host);
}
}
internal string SmtpAddress{
get{
return String.Format(CultureInfo.InvariantCulture, "<{0}>", Address);
}
}
///
/// this returns the full address with quoted display name.
/// i.e. "some email address display name"
/// if displayname is not provided then this returns only user@host (no angle brackets)
///
///
public override string ToString() {
if (String.IsNullOrEmpty(DisplayName)) {
return this.Address;
}
else {
return String.Format("\"{0}\" {1}", DisplayName, SmtpAddress);
}
}
public override bool Equals(object value) {
if (value == null) {
return false;
}
return ToString().Equals(value.ToString(),StringComparison.InvariantCultureIgnoreCase);
}
public override int GetHashCode(){
return ToString().GetHashCode();
}
static EncodedStreamFactory encoderFactory = new EncodedStreamFactory();
// Encodes the full email address, folding as needed
internal string Encode(int charsConsumed)
{
string encodedAddress = String.Empty;
IEncodableStream encoder;
byte[] buffer;
Debug.Assert(this.Address != null, "address was null");
//do we need to take into account the Display name? If so, encode it
if (!String.IsNullOrEmpty(this.displayName))
{
//figure out the encoding type. If it's all ASCII and contains no CRLF then
//it does not need to be encoded for parity with other email clients. We will
//however fold at the end of the display name so that the email address itself can
//be appended.
if (MimeBasePart.IsAscii(this.displayName, false))
{
encodedAddress = String.Format("\"{0}\"", this.displayName);
}
else
{
//encode the displayname since it's non-ascii
encoder = encoderFactory.GetEncoderForHeader(this.displayNameEncoding, false, charsConsumed);
buffer = displayNameEncoding.GetBytes(this.displayName);
encoder.EncodeBytes(buffer, 0, buffer.Length);
encodedAddress = encoder.GetEncodedString();
}
//the extra space is because there should be a non-printable whitespace char
//following the fold (CRLF) and there is supposed to be a space between the display name and
//the address so this is necessary.
encodedAddress += "\r\n ";
}
//now we have the encoded display name (if present), we need to append the address to it.
if (!String.IsNullOrEmpty(encodedAddress))
{
//address should be enclosed in <> when a display name is present
encodedAddress += SmtpAddress;
}
else
{
//no display name, just return the address
encodedAddress = this.Address;
}
return encodedAddress;
}
}
}
// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
Link Menu

This book is available now!
Buy at Amazon US or
Buy at Amazon UK
- DataRelation.cs
- SmtpMail.cs
- KoreanLunisolarCalendar.cs
- ErrorEventArgs.cs
- XhtmlTextWriter.cs
- TextServicesCompartmentContext.cs
- WebConfigurationFileMap.cs
- ProtocolsConfigurationEntry.cs
- Clipboard.cs
- WindowsEditBoxRange.cs
- RSAPKCS1SignatureDeformatter.cs
- SQLMoney.cs
- DirtyTextRange.cs
- FrameworkObject.cs
- WorkflowTransactionOptions.cs
- ListBox.cs
- Cell.cs
- MappingSource.cs
- EventSource.cs
- x509store.cs
- NameSpaceExtractor.cs
- itemelement.cs
- RegexFCD.cs
- MultiViewDesigner.cs
- XmlSchemaSimpleTypeRestriction.cs
- FixedStringLookup.cs
- CharAnimationUsingKeyFrames.cs
- ProcessHost.cs
- StringComparer.cs
- DirectionalLight.cs
- BasicViewGenerator.cs
- PageSettings.cs
- LayoutInformation.cs
- ADRole.cs
- BitVector32.cs
- ImmComposition.cs
- COM2PropertyDescriptor.cs
- LoginName.cs
- HtmlTableCellCollection.cs
- HttpApplicationStateBase.cs
- AttributeXamlType.cs
- ScopedKnownTypes.cs
- DataGridColumnStyleMappingNameEditor.cs
- EdmComplexPropertyAttribute.cs
- Encoder.cs
- PeerCollaboration.cs
- FontUnitConverter.cs
- MimeMultiPart.cs
- FormViewUpdatedEventArgs.cs
- prompt.cs
- DataServiceHostFactory.cs
- AnnotationStore.cs
- TextTreePropertyUndoUnit.cs
- basemetadatamappingvisitor.cs
- UrlPath.cs
- Sequence.cs
- XmlStrings.cs
- DbParameterCollectionHelper.cs
- DropShadowBitmapEffect.cs
- MetafileHeaderWmf.cs
- XmlParser.cs
- hresults.cs
- UserThread.cs
- Monitor.cs
- LiteralTextContainerControlBuilder.cs
- TraceContext.cs
- DependencyProperty.cs
- XPathQilFactory.cs
- ConfigXmlSignificantWhitespace.cs
- ListBox.cs
- ReachDocumentSequenceSerializer.cs
- JoinSymbol.cs
- StatusBarItemAutomationPeer.cs
- XPathDocumentBuilder.cs
- PenLineCapValidation.cs
- ZoomingMessageFilter.cs
- IntersectQueryOperator.cs
- OleDbReferenceCollection.cs
- _BaseOverlappedAsyncResult.cs
- CallTemplateAction.cs
- SqlGenerator.cs
- RandomNumberGenerator.cs
- MessageQueuePermissionEntry.cs
- X509Certificate.cs
- RoleManagerEventArgs.cs
- _Rfc2616CacheValidators.cs
- AuthenticationConfig.cs
- Misc.cs
- COMException.cs
- ProcessModelSection.cs
- ValidatingPropertiesEventArgs.cs
- LineServices.cs
- EntityDataSource.cs
- RegistryConfigurationProvider.cs
- GPRECT.cs
- BufferedOutputStream.cs
- LinqDataSourceHelper.cs
- IncrementalHitTester.cs
- PseudoWebRequest.cs
- ConfigurationElement.cs