MailMessage.Headers Свойство

Определение

Возвращает заголовки электронной почты, передаваемые с данным сообщением.

public:
 property System::Collections::Specialized::NameValueCollection ^ Headers { System::Collections::Specialized::NameValueCollection ^ get(); };
public System.Collections.Specialized.NameValueCollection Headers { get; }
member this.Headers : System.Collections.Specialized.NameValueCollection
Public ReadOnly Property Headers As NameValueCollection

Значение свойства

Объект NameValueCollection , содержащий заголовки сообщений электронной почты.

Примеры

В следующем примере кода показано отображение заголовков почтового сообщения.

static void CreateMessageWithAttachment4( String^ server, String^ to )
{
   
   // Specify the file to be attached and sent.
   // This example uses a file on a UNC share.
   String^ file = L"\\\\share3\\c$\\reports\\data.xls";
   
   // Create a message and set up the recipients.
   MailMessage^ message = gcnew MailMessage( L"ReportMailer@contoso.com",to,L"Quarterly data report",L"See the attached spreadsheet." );
   
   // Create  the file attachment for this email message.
   Attachment^ data = gcnew Attachment("qtr3.xls", MediaTypeNames::Application::Octet);
   
   // Add time stamp information for the file.
   ContentDisposition^ disposition = data->ContentDisposition;
   disposition->CreationDate = System::IO::File::GetCreationTime( file );
   disposition->ModificationDate = System::IO::File::GetLastWriteTime( file );
   disposition->ReadDate = System::IO::File::GetLastAccessTime( file );
   disposition->DispositionType = DispositionTypeNames::Attachment;
   
   // Add the file attachment to this email message.
   message->Attachments->Add( data );
   
   //Send the message.
   SmtpClient^ client = gcnew SmtpClient( server );
   
   // Add credentials if the SMTP server requires them.
   client->Credentials = dynamic_cast<ICredentialsByHost^>(CredentialCache::DefaultNetworkCredentials);
   client->Send( message );
   
   // Display the message headers.
   array<String^>^keys = message->Headers->AllKeys;
   Console::WriteLine( L"Headers" );
   IEnumerator^ myEnum3 = keys->GetEnumerator();
   while ( myEnum3->MoveNext() )
   {
      String^ s = safe_cast<String^>(myEnum3->Current);
      Console::WriteLine( L"{0}:", s );
      Console::WriteLine( L"    {0}", message->Headers[ s ] );
   }

   data->~Attachment();
   client->~SmtpClient();
}
public static void CreateMessageWithAttachment4(string server, string to)
{
    // Specify the file to be attached and sent.
    // This example uses a file on a UNC share.
    string file = @"\\share3\c$\reports\data.xls";
    // Create a message and set up the recipients.
    MailMessage message = new MailMessage(
       "ReportMailer@contoso.com",
       to,
       "Quarterly data report",
       "See the attached spreadsheet.");

    // Create  the file attachment for this email message.
    Attachment data = new Attachment("qtr3.xls", MediaTypeNames.Application.Octet);
    // Add time stamp information for the file.
    ContentDisposition disposition = data.ContentDisposition;
    disposition.CreationDate = System.IO.File.GetCreationTime(file);
    disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
    disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
    disposition.DispositionType = DispositionTypeNames.Attachment;
    // Add the file attachment to this email message.
    message.Attachments.Add(data);
    //Send the message.
    SmtpClient client = new SmtpClient(server);
    // Add credentials if the SMTP server requires them.
    client.Credentials = (ICredentialsByHost)CredentialCache.DefaultNetworkCredentials;
    client.Send(message);
    // Display the message headers.
    string[] keys = message.Headers.AllKeys;
    Console.WriteLine("Headers");
    foreach (string s in keys)
    {
        Console.WriteLine("{0}:", s);
        Console.WriteLine("    {0}", message.Headers[s]);
    }
    data.Dispose();
}
Public Shared Sub CreateMessageWithAttachment4(ByVal server As String, ByVal [to] As String)
    ' Specify the file to be attached And sent.
    ' This example uses a file on a UNC share.
    Dim file As String = "\\share3\c$\reports\data.xls"
    Dim message As MailMessage = New MailMessage("ReportMailer@contoso.com", [to], "Quarterly data report", "See the attached spreadsheet.")
    ' Create  the file attachment for this email message.
    Dim data As Attachment = New Attachment("qtr3.xls", MediaTypeNames.Application.Octet)
    ' Add time stamp information for the file.
    Dim disposition As ContentDisposition = data.ContentDisposition
    disposition.CreationDate = System.IO.File.GetCreationTime(file)
    disposition.ModificationDate = System.IO.File.GetLastWriteTime(file)
    disposition.ReadDate = System.IO.File.GetLastAccessTime(file)
    disposition.DispositionType = DispositionTypeNames.Attachment
    ' Add the file attachment to this email message.
    message.Attachments.Add(data)
    'Send the message.
    Dim client As SmtpClient = New SmtpClient(server)
    ' Add credentials if the SMTP server requires them.
    client.Credentials = CType(CredentialCache.DefaultNetworkCredentials, ICredentialsByHost)
    client.Send(message)
    ' Display the message headers.
    Dim keys As String() = message.Headers.AllKeys
    Console.WriteLine("Headers")

    For Each s As String In keys
        Console.WriteLine("{0}:", s)
        Console.WriteLine("    {0}", message.Headers(s))
    Next

    data.Dispose()
End Sub

Комментарии

Свойство Headers позволяет приложению получить доступ к коллекции заголовков для сообщения. Хотя эта коллекция доступна только для чтения (новую коллекцию нельзя задать), пользовательские заголовки можно добавлять в коллекцию или удалять из нее. Все добавленные пользовательские заголовки будут включены при отправке экземпляра MailMessage . Перед отправкой сообщения в коллекцию включаются только заголовки, специально добавленные в эту коллекцию Headers в свойстве . После отправки экземпляра MailMessageHeaders свойство также будет включать заголовки, которые задаются с помощью связанных свойств класса или параметров, передаваемых MailMessage при MailMessage использовании для инициализации MailMessage объекта.

Если некоторые заголовки электронной почты имеют неправильный формат, это может привести к повреждению сообщения электронной почты. Поэтому любой заголовок почты в коллекции headers, который можно задать с помощью свойства MailMessage класса , следует задавать только с помощью MailMessage свойства класса или в качестве параметра, передаваемого MailMessage при инициализации MailMessage объекта . Следующий список заголовков почты не следует добавлять с помощью Headers свойства , а все значения, заданные для этих заголовков с помощью Headers свойства , будут удалены или перезаписаны при отправке сообщения:

  • Скрытая копия

  • Копия

  • Идентификатор содержимого

  • Content-Location

  • Кодирование передачи содержимого

  • Content-Type

  • Date

  • Исходный тип

  • Важность

  • MIME-Version

  • Приоритет

  • Reply-To

  • Отправитель

  • Кому

  • Приоритет по оси X

Если приложение не указывает заголовок X-Sender с помощью Headers свойства , MailMessage класс создаст его при отправке сообщения.

Отправитель, получатель, тема и текст сообщения электронной почты могут быть указаны в качестве параметров, если MailMessage используется для инициализации MailMessage объекта . Эти параметры также можно задать или получить к ней MailMessage доступ с помощью свойств объекта .

Заголовки и элементы основного почтового сообщения для сообщения можно задать с помощью следующих свойств MailMessage класса .

Заголовок или часть почты Свойство.
Вложения Attachments
Слепые углеродные копии (BCC) Bcc
Углеродные копии (CC) CC
Content-Type BodyEncoding
Кодировка для пользовательских заголовков HeadersEncoding
Текст сообщения Body
Приоритет Priority
Recipient To
Reply-To ReplyToList
Отправитель From
Субъект Subject

Применяется к