Attachment Класс

Определение

Представляет вложение в сообщение электронной почты.

public ref class Attachment : System::Net::Mail::AttachmentBase
public class Attachment : System.Net.Mail.AttachmentBase
type Attachment = class
    inherit AttachmentBase
Public Class Attachment
Inherits AttachmentBase
Наследование
Attachment

Примеры

В следующем примере кода показано вложение файла в сообщение электронной почты.

static void CreateMessageWithAttachment( String^ server )
{
   
   // Specify the file to be attached and sent.
   // This example assumes that a file named Data.xls exists in the
   // current working directory.
   String^ file = L"data.xls";
   
   // Create a message and set up the recipients.
   MailMessage^ message = gcnew MailMessage( L"jane@contoso.com",L"ben@contoso.com",L"Quarterly data report.",L"See the attached spreadsheet." );
   
   // Create  the file attachment for this email message.
   Attachment^ data = gcnew Attachment(file, 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 );
   
   // 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 = CredentialCache::DefaultNetworkCredentials;
   client->Send( message );
   
   // Display the values in the ContentDisposition for the attachment.
   ContentDisposition^ cd = data->ContentDisposition;
   Console::WriteLine( L"Content disposition" );
   Console::WriteLine( cd );
   Console::WriteLine( L"File {0}", cd->FileName );
   Console::WriteLine( L"Size {0}", cd->Size );
   Console::WriteLine( L"Creation {0}", cd->CreationDate );
   Console::WriteLine( L"Modification {0}", cd->ModificationDate );
   Console::WriteLine( L"Read {0}", cd->ReadDate );
   Console::WriteLine( L"Inline {0}", cd->Inline );
   Console::WriteLine( L"Parameters: {0}", cd->Parameters->Count );
   IEnumerator^ myEnum1 = cd->Parameters->GetEnumerator();
   while ( myEnum1->MoveNext() )
   {
      DictionaryEntry^ d = safe_cast<DictionaryEntry^>(myEnum1->Current);
      Console::WriteLine( L"{0} = {1}", d->Key, d->Value );
   }

   data->~Attachment();
   client->~SmtpClient();
}
public static void CreateMessageWithAttachment(string server)
{
    // Specify the file to be attached and sent.
    // This example assumes that a file named Data.xls exists in the
    // current working directory.
    string file = "data.xls";
    // Create a message and set up the recipients.
    MailMessage message = new MailMessage(
        "jane@contoso.com",
        "ben@contoso.com",
        "Quarterly data report.",
        "See the attached spreadsheet.");

    // Create  the file attachment for this email message.
    Attachment data = new Attachment(file, 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);
    // 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 = CredentialCache.DefaultNetworkCredentials;

    try
    {
        client.Send(message);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}",
            ex.ToString());
    }
    // Display the values in the ContentDisposition for the attachment.
    ContentDisposition cd = data.ContentDisposition;
    Console.WriteLine("Content disposition");
    Console.WriteLine(cd.ToString());
    Console.WriteLine("File {0}", cd.FileName);
    Console.WriteLine("Size {0}", cd.Size);
    Console.WriteLine("Creation {0}", cd.CreationDate);
    Console.WriteLine("Modification {0}", cd.ModificationDate);
    Console.WriteLine("Read {0}", cd.ReadDate);
    Console.WriteLine("Inline {0}", cd.Inline);
    Console.WriteLine("Parameters: {0}", cd.Parameters.Count);
    foreach (DictionaryEntry d in cd.Parameters)
    {
        Console.WriteLine("{0} = {1}", d.Key, d.Value);
    }
    data.Dispose();
}

Комментарии

Класс Attachment используется с классом MailMessage . Все сообщения включают значение Body, содержащее содержимое сообщения. В дополнение к тексту может потребоваться отправить дополнительные файлы. Они отправляются как вложения и представляются как Attachment экземпляры. Чтобы добавить вложение в почтовое сообщение, добавьте его в коллекцию MailMessage.Attachments .

Содержимое вложения может быть StringStreamименем или именем файла. Содержимое вложения можно указать с помощью любого конструктора Attachment .

Сведения о заголовке miME Content-Type для вложения представлены свойством ContentType . Заголовок Content-Type указывает тип носителя и подтип и все связанные параметры. Используется ContentType для получения экземпляра, связанного с вложением.

Заголовок MIME Content-Disposition представлен свойством ContentDisposition . Заголовок Content-Disposition указывает метки времени представления и файла для вложения. Заголовок Content-Disposition отправляется только в том случае, если вложение является файлом. ContentDisposition Используйте свойство для получения экземпляра, связанного с вложением.

Заголовок MIME Content-Transfer-Encoding представлен свойством TransferEncoding .

Конструкторы

Attachment(Stream, ContentType)

Инициализирует новый экземпляр класса Attachment с указанным потоком и типом содержимого.

Attachment(Stream, String)

Инициализирует новый экземпляр класса Attachment с указанными потоком и именем.

Attachment(Stream, String, String)

Инициализирует новый экземпляр класса Attachment с указанными потоком, именем и информацией о типе MIME.

Attachment(String)

Инициализирует новый экземпляр класса Attachment с указанной строкой содержимого.

Attachment(String, ContentType)

Инициализирует новый экземпляр класса Attachment с указанной строкой содержимого и ContentType.

Attachment(String, String)

Инициализирует новый экземпляр класса Attachment с указанной строкой содержимого и информацией о типе MIME.

Свойства

ContentDisposition

Возвращает расположение содержимого MIME для этого вложения.

ContentId

Возвращает или задает идентификатор содержимого MIME для этого вложения.

(Унаследовано от AttachmentBase)
ContentStream

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

(Унаследовано от AttachmentBase)
ContentType

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

(Унаследовано от AttachmentBase)
Name

Возвращает или задает значение имени типа содержимого MIME, связанного с данным вложением.

NameEncoding

Указывает кодировку для AttachmentName.

TransferEncoding

Возвращает или задает кодировку данного вложения.

(Унаследовано от AttachmentBase)

Методы

CreateAttachmentFromString(String, ContentType)

Создает почтовое вложение, используя содержимое указанной строки и заданный ContentType.

CreateAttachmentFromString(String, String)

Создает почтовое вложение, используя содержимое указанной строки и заданное имя типа содержимого MIME.

CreateAttachmentFromString(String, String, Encoding, String)

Создает почтовое вложение, используя содержимое указанной строки, заданное имя типа содержимого MIME, кодировку символов и информацию заголовка MIME для вложения.

Dispose()

Освобождает ресурсы, используемые объектом AttachmentBase.

(Унаследовано от AttachmentBase)
Dispose(Boolean)

Освобождает неуправляемые ресурсы, используемые объектом AttachmentBase, а при необходимости освобождает также управляемые ресурсы.

(Унаследовано от AttachmentBase)
Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

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