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

Определение

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

Перегрузки

Attachment(String)

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

Attachment(Stream, ContentType)

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

Attachment(Stream, String)

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

Attachment(String, ContentType)

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

Attachment(String, String)

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

Attachment(Stream, String, String)

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

Attachment(String)

Исходный код:
Attachment.cs
Исходный код:
Attachment.cs
Исходный код:
Attachment.cs

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

public:
 Attachment(System::String ^ fileName);
public Attachment (string fileName);
new System.Net.Mail.Attachment : string -> System.Net.Mail.Attachment
Public Sub New (fileName As String)

Параметры

fileName
String

Значение String, содержащее путь к файлу для создания этого вложения.

Исключения

fileName имеет значение null.

Параметр fileName пуст.

Примеры

В следующем примере кода показано, как вызвать этот конструктор.

static void CreateMessageInlineAttachment2( String^ server, String^ textMessage )
{
   
   // Create a message and set up the recipients.
   MailMessage^ message = gcnew MailMessage( L"jane@contoso.com",L"ben@contoso.com",L"A text message for you.",L"Message: " );
   
   // Attach the message string to this email message.
   Attachment^ data = gcnew Attachment( textMessage );
   
   // Send textMessage as part of the email body.
   message->Attachments->Add( data );
   ContentType^ content = data->ContentType;
   content->MediaType = MediaTypeNames::Text::Plain;
   
   //Send the message.
   // Include credentials if the server requires them.
   SmtpClient^ client = gcnew SmtpClient( server );
   client->Credentials = CredentialCache::DefaultNetworkCredentials;
   client->Send( message );
   data->~Attachment();
   client->~SmtpClient();
}
public static void CreateMessageInlineAttachment2(string server, string
textMessage)
{
    // Create a message and set up the recipients.
    MailMessage message = new MailMessage(
       "jane@contoso.com",
       "ben@contoso.com",
       "A text message for you.",
       "Message: ");

    // Attach the message string to this email message.
    Attachment data = new Attachment(textMessage);
    // Send textMessage as part of the email body.
    message.Attachments.Add(data);
    ContentType content = data.ContentType;
    content.MediaType = MediaTypeNames.Text.Plain;
    //Send the message.
    // Include credentials if the server requires them.
    SmtpClient client = new SmtpClient(server);
    client.Credentials = CredentialCache.DefaultNetworkCredentials;

    try
    {
        client.Send(message);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception caught in CreateMessageInlineAttachment2: {0}",
            ex.ToString());
    }
    data.Dispose();
}

Комментарии

Свойства задаются следующим образом:

Свойство. Значение
MediaType Plain.
TransferEncoding QuotedPrintable.

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

Attachment(Stream, ContentType)

Исходный код:
Attachment.cs
Исходный код:
Attachment.cs
Исходный код:
Attachment.cs

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

public:
 Attachment(System::IO::Stream ^ contentStream, System::Net::Mime::ContentType ^ contentType);
public Attachment (System.IO.Stream contentStream, System.Net.Mime.ContentType contentType);
new System.Net.Mail.Attachment : System.IO.Stream * System.Net.Mime.ContentType -> System.Net.Mail.Attachment
Public Sub New (contentStream As Stream, contentType As ContentType)

Параметры

contentStream
Stream

Доступный для чтения объект Stream, который содержит содержимое данного вложения.

contentType
ContentType

Объект ContentType, описывающий данные параметра contentStream.

Исключения

contentType имеет значение null.

-или-

contentStream имеет значение null.

Примеры

В следующем примере кода показано, как вызвать этот конструктор.

// The following example sends a summary of a log file as the message
// and the log as an email attachment.
static void SendErrorLog( String^ server, String^ recipientList )
{
   
   // Create a message from logMailer@contoso.com to recipientList.
   MailMessage^ message = gcnew MailMessage( L"logMailer@contoso.com",recipientList );
   message->Subject = L"Error Log report";
   String^ fileName = L"log.txt";
   
   // Get the file stream for the error log.
   // Requires the System.IO namespace.
   FileStream^ fs = gcnew FileStream( fileName,FileMode::Open,FileAccess::Read );
   StreamReader^ s = gcnew StreamReader( fs );
   int errors = 0;
   while ( s->ReadLine() != nullptr )
   {
      
      // Process each line from the log file here.
      errors++;
   }

   message->Body = String::Format( L"{0} errors in log as of {1}", errors, DateTime::Now );
   
   // Close the stream reader. This also closes the file.
   s->Close();
   
   // Re-open the file at the beginning to make the attachment.
   fs = gcnew FileStream( fileName,FileMode::Open,FileAccess::Read );
   
   // Make a contentType indicating that the log data
   // that is attached is plain text.
   ContentType^ ct = gcnew ContentType( MediaTypeNames::Text::Plain );
   
   // Attach the log file stream to the email message.
   Attachment^ data = gcnew Attachment( fs,ct );
   ContentDisposition^ disposition = data->ContentDisposition;
   
   // Suggest a file name for the attachment.
   disposition->FileName = String::Format( L"log{0}.txt", DateTime::Now );
   
   // Add the attachment to the message.
   message->Attachments->Add( data );
   
   // Send the message.
   // Include credentials if the server requires them.
   SmtpClient^ client = gcnew SmtpClient( server );
   client->Credentials = CredentialCache::DefaultNetworkCredentials;
   client->Send( message );
   data->~Attachment();
   client->~SmtpClient();
   
   // Close the log file.
   fs->Close();
}
// The following example sends a summary of a log file as the message
// and the log as an email attachment.
public static void SendErrorLog(string server, string recipientList)
{
    // Create a message from logMailer@contoso.com to recipientList.
    MailMessage message = new MailMessage(
       "logMailer@contoso.com", recipientList);

    message.Subject = "Error Log report";
    string fileName = "log.txt";
    // Get the file stream for the error log.
    // Requires the System.IO namespace.
    FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
    StreamReader s = new StreamReader(fs);
    int errors = 0;
    while (s.ReadLine() != null)
    {
        // Process each line from the log file here.
        errors++;
    }
    // The email message summarizes the data found in the log.
    message.Body = String.Format("{0} errors in log as of {1}",
        errors, DateTime.Now);
    // Close the stream reader. This also closes the file.
    s.Close();
    // Re-open the file at the beginning to make the attachment.
    fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
    // Make a contentType indicating that the log data
    // that is attached is plain text.
    ContentType ct = new ContentType(MediaTypeNames.Text.Plain);
    // Attach the log file stream to the email message.
    Attachment data = new Attachment(fs, ct);
    ContentDisposition disposition = data.ContentDisposition;
    // Suggest a file name for the attachment.
    disposition.FileName = "log" + DateTime.Now.ToString() + ".txt";
    // Add the attachment to the message.
    message.Attachments.Add(data);
    // Send the message.
    // Include credentials if the server requires them.
    SmtpClient client = new SmtpClient(server);
    client.Credentials = CredentialCache.DefaultNetworkCredentials;

    try
    {
        client.Send(message);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception caught in SendErrorLog: {0}",
            ex.ToString());
    }
    data.Dispose();
    // Close the log file.
    fs.Close();
}

Комментарии

Свойство TransferEncoding имеет значение Base64.

Если свойство потока CanSeek имеет значение false, вложение и объект , MailMessage содержащий его, нельзя использовать повторно. Необходимо предоставить поток, в который можно выполнить поиск для повторного использования вложения.

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

Attachment(Stream, String)

Исходный код:
Attachment.cs
Исходный код:
Attachment.cs
Исходный код:
Attachment.cs

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

public:
 Attachment(System::IO::Stream ^ contentStream, System::String ^ name);
public Attachment (System.IO.Stream contentStream, string? name);
public Attachment (System.IO.Stream contentStream, string name);
new System.Net.Mail.Attachment : System.IO.Stream * string -> System.Net.Mail.Attachment
Public Sub New (contentStream As Stream, name As String)

Параметры

contentStream
Stream

Доступный для чтения объект Stream, который содержит содержимое данного вложения.

name
String

Объект String, содержащий значение свойства Name объекта ContentType, связанного с данным вложением. Это значение может быть равно null.

Исключения

contentStream имеет значение null.

Примеры

В следующем примере кода показано, как вызвать этот конструктор.

// The following example sends a summary of a log file as the message
// and the log as an email attachment.
static void SendNamedErrorLog( String^ server, String^ recipientList )
{
   
   // Create a message from logMailer@contoso.com to recipientList.
   MailMessage^ message = gcnew MailMessage( L"logMailer@contoso.com",recipientList );
   message->Subject = L"Error Log report";
   String^ fileName = L"log.txt";
   
   // Get the file stream for the error log.
   // Requires the System.IO namespace.
   FileStream^ fs = gcnew FileStream( fileName,FileMode::Open,FileAccess::Read );
   StreamReader^ s = gcnew StreamReader( fs );
   int errors = 0;
   while ( s->ReadLine() != nullptr )
   {
      
      // Process each line from the log file here.
      errors++;
   }

   message->Body = String::Format( L"{0} errors in log as of {1}", errors, DateTime::Now );
   
   // Close the stream reader. This also closes the file.
   s->Close();
   
   // Re-open the file at the beginning to make the attachment.
   fs = gcnew FileStream( fileName,FileMode::Open,FileAccess::Read );
   
   // Make a ContentType indicating that the log data
   // that is attached is plain text and is named.
   ContentType^ ct = gcnew ContentType;
   ct->MediaType = MediaTypeNames::Text::Plain;
   ct->Name = String::Format( L"log{0}.txt", DateTime::Now );
   
   // Create the attachment.
   Attachment^ data = gcnew Attachment( fs,ct );
   
   // Add the attachment to the message.
   message->Attachments->Add( data );
   
   // Send the message.
   // Include credentials if the server requires them.
   SmtpClient^ client = gcnew SmtpClient( server );
   client->Credentials = CredentialCache::DefaultNetworkCredentials;
   client->Send( message );
   data->~Attachment();
   client->~SmtpClient();
   
   // Close the log file.
   fs->Close();
   return;
}
// The following example sends a summary of a log file as the message
// and the log as an email attachment.
public static void SendNamedErrorLog(string server, string recipientList)
{
    // Create a message from logMailer@contoso.com to recipientList.
    MailMessage message = new MailMessage(
       "logMailer@contoso.com", recipientList);

    message.Subject = "Error Log report";
    string fileName = "log.txt";
    // Get the file stream for the error log.
    // Requires the System.IO namespace.
    FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
    StreamReader s = new StreamReader(fs);
    int errors = 0;
    while (s.ReadLine() != null)
    {
        // Process each line from the log file here.
        errors++;
    }
    // The email message summarizes the data found in the log.
    message.Body = String.Format("{0} errors in log as of {1}",
        errors, DateTime.Now);
    // Close the stream reader. This also closes the file.
    s.Close();
    // Re-open the file at the beginning to make the attachment.
    fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
    // Make a ContentType indicating that the log data
    // that is attached is plain text and is named.
    ContentType ct = new ContentType();
    ct.MediaType = MediaTypeNames.Text.Plain;
    ct.Name = "log" + DateTime.Now.ToString() + ".txt";
    // Create the attachment.
    Attachment data = new Attachment(fs, ct);
    // Add the attachment to the message.
    message.Attachments.Add(data);
    // Send the message.
    // Include credentials if the server requires them.
    SmtpClient client = new SmtpClient(server);
    client.Credentials = CredentialCache.DefaultNetworkCredentials;

    try
    {
        client.Send(message);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception caught in SendNamedErrorLog: {0}",
            ex.ToString());
    }
    data.Dispose();
    // Close the log file.
    fs.Close();
    return;
}

Комментарии

Если name значение не null равно ( String.Empty ""), ContentType для этого вложения создается со свойством Name , равным name. Свойство TransferEncoding имеет значение Base64.

Если свойство потока CanSeek имеет значение false, вложение и объект , MailMessage содержащий его, нельзя использовать повторно. Для повторного использования вложения необходимо предоставить поток, в который можно выполнить поиск.

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

Attachment(String, ContentType)

Исходный код:
Attachment.cs
Исходный код:
Attachment.cs
Исходный код:
Attachment.cs

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

public:
 Attachment(System::String ^ fileName, System::Net::Mime::ContentType ^ contentType);
public Attachment (string fileName, System.Net.Mime.ContentType contentType);
new System.Net.Mail.Attachment : string * System.Net.Mime.ContentType -> System.Net.Mail.Attachment
Public Sub New (fileName As String, contentType As ContentType)

Параметры

fileName
String

Значение String, содержащее путь к файлу для создания этого вложения.

contentType
ContentType

Объект ContentType, описывающий данные параметра fileName.

Исключения

fileName имеет значение null.

mediaType имеет неправильный формат.

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

Attachment(String, String)

Исходный код:
Attachment.cs
Исходный код:
Attachment.cs
Исходный код:
Attachment.cs

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

public:
 Attachment(System::String ^ fileName, System::String ^ mediaType);
public Attachment (string fileName, string? mediaType);
public Attachment (string fileName, string mediaType);
new System.Net.Mail.Attachment : string * string -> System.Net.Mail.Attachment
Public Sub New (fileName As String, mediaType As String)

Параметры

fileName
String

Объект String, который содержит содержимое данного вложения.

mediaType
String

Объект String, который содержит информацию MIME Content-Header для данного вложения. Это значение может быть равно null.

Исключения

fileName имеет значение null.

mediaType имеет неправильный формат.

Примеры

В следующем примере кода показано, как вызвать этот конструктор.

static void CreateMessageInlineAttachment( String^ server, String^ textMessage )
{
   
   // Create a message and set up the recipients.
   MailMessage^ message = gcnew MailMessage( L"jane@contoso.com",L"ben@contoso.com",L"An inline text message for you.",L"Message: " );
   
   // Attach the message string to this email message.
   Attachment^ data = gcnew Attachment( textMessage,MediaTypeNames::Text::Plain );
   
   // Send textMessage as part of the email body.
   message->Attachments->Add( data );
   ContentDisposition^ disposition = data->ContentDisposition;
   disposition->Inline = true;
   
   //Send the message.
   // Include credentials if the server requires them.
   SmtpClient^ client = gcnew SmtpClient( server );
   client->Credentials = CredentialCache::DefaultNetworkCredentials;
   client->Send( message );
   data->~Attachment();
   client->~SmtpClient();
}
public static void CreateMessageInlineAttachment(string server, string
textMessage)
{
    // Create a message and set up the recipients.
    MailMessage message = new MailMessage(
       "jane@contoso.com",
       "ben@contoso.com",
       "An inline text message for you.",
       "Message: ");

    // Attach the message string to this email message.
    Attachment data = new Attachment(textMessage, MediaTypeNames.Text.Plain);
    // Send textMessage as part of the email body.
    message.Attachments.Add(data);
    ContentDisposition disposition = data.ContentDisposition;
    disposition.Inline = true;
    //Send the message.
    // Include credentials if the server requires them.
    SmtpClient client = new SmtpClient(server);
    client.Credentials = CredentialCache.DefaultNetworkCredentials;

    try
    {
        client.Send(message);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception caught in CreateMessageInlineAttachment: {0}",
            ex.ToString());
    }
    data.Dispose();
}

Комментарии

Если mediaType имеет значение null или равно String.Empty (""), свойству MediaType для этого вложения присваивается значение Plain. Если mediaType не является null и не является строкой нулевой длины, она используется для создания , связанного ContentType с этим вложением.

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

Attachment(Stream, String, String)

Исходный код:
Attachment.cs
Исходный код:
Attachment.cs
Исходный код:
Attachment.cs

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

public:
 Attachment(System::IO::Stream ^ contentStream, System::String ^ name, System::String ^ mediaType);
public Attachment (System.IO.Stream contentStream, string? name, string? mediaType);
public Attachment (System.IO.Stream contentStream, string name, string mediaType);
new System.Net.Mail.Attachment : System.IO.Stream * string * string -> System.Net.Mail.Attachment
Public Sub New (contentStream As Stream, name As String, mediaType As String)

Параметры

contentStream
Stream

Доступный для чтения объект Stream, который содержит содержимое данного вложения.

name
String

Объект String, содержащий значение свойства Name объекта ContentType, связанного с данным вложением. Это значение может быть равно null.

mediaType
String

Объект String, который содержит информацию MIME Content-Header для данного вложения. Это значение может быть равно null.

Исключения

stream имеет значение null.

mediaType имеет неправильный формат.

Примеры

В следующем примере кода показано, как вызвать этот конструктор.

// The following example sends a summary of a log file as the message
// and the log as an email attachment.
static void SendNamedAndTypedErrorLog( String^ server, String^ recipientList )
{
   
   // Create a message from logMailer@contoso.com to recipientList.
   MailMessage^ message = gcnew MailMessage( L"logMailer@contoso.com",recipientList );
   message->Subject = L"Error Log report";
   String^ fileName = L"log.txt";
   
   // Get the file stream for the error log.
   // Requires the System.IO namespace.
   FileStream^ fs = gcnew FileStream( fileName,FileMode::Open,FileAccess::Read );
   StreamReader^ s = gcnew StreamReader( fs );
   int errors = 0;
   while ( s->ReadLine() != nullptr )
   {
      
      // Process each line from the log file here.
      errors++;
   }

   message->Body = String::Format( L"{0} errors in log as of {1}", errors, DateTime::Now );
   
   // Close the stream reader. This also closes the file.
   s->Close();
   
   // Re-open the file at the beginning to make the attachment.
   fs = gcnew FileStream( fileName,FileMode::Open,FileAccess::Read );
   
   // Create a name for the log data file.
   String^ name = String::Format( L"log{0}.txt", DateTime::Now );
   
   // Create the attachment, name it, and specify the MIME type.
   Attachment^ data = gcnew Attachment( fs,name,MediaTypeNames::Text::Plain );
   
   // Add the attachment to the message.
   message->Attachments->Add( data );
   
   // Send the message.
   // Include credentials if the server requires them.
   SmtpClient^ client = gcnew SmtpClient( server );
   client->Credentials = CredentialCache::DefaultNetworkCredentials;
   client->Send( message );
   data->~Attachment();
   client->~SmtpClient();
   
   // Close the log file.
   fs->Close();
}
// The following example sends a summary of a log file as the message
// and the log as an email attachment.
public static void SendNamedAndTypedErrorLog(string server, string recipientList)
{
    // Create a message from logMailer@contoso.com to recipientList.
    MailMessage message = new MailMessage(
       "logMailer@contoso.com", recipientList);

    message.Subject = "Error Log report";
    string fileName = "log.txt";
    // Get the file stream for the error log.
    // Requires the System.IO namespace.
    FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
    StreamReader s = new StreamReader(fs);
    int errors = 0;
    while (s.ReadLine() != null)
    {
        // Process each line from the log file here.
        errors++;
    }
    // The email message summarizes the data found in the log.
    message.Body = String.Format("{0} errors in log as of {1}",
        errors, DateTime.Now);
    // Close the stream reader. This also closes the file.
    s.Close();
    // Re-open the file at the beginning to make the attachment.
    fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
    // Create a name for the log data file.
    string name = "log" + DateTime.Now.ToString() + ".txt";
    // Create the attachment, name it, and specify the MIME type.
    Attachment data = new Attachment(fs, name, MediaTypeNames.Text.Plain);
    // Add the attachment to the message.
    message.Attachments.Add(data);
    // Send the message.
    // Include credentials if the server requires them.
    SmtpClient client = new SmtpClient(server);
    client.Credentials = CredentialCache.DefaultNetworkCredentials;

    try
    {
        client.Send(message);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception caught in SendNamedAndTypedErrorLog: {0}",
            ex.ToString());
    }
    data.Dispose();
    // Close the log file.
    fs.Close();
}

Комментарии

Если mediaType параметр не nullString.Empty равен (""), он используется для создания класса, связанного ContentType с этим вложением.

Если mediaType и оба name содержат Name сведения, используется значение, указанное в name . Свойство TransferEncoding имеет значение Base64.

Если свойство потока CanSeek имеет значение false, вложение и объект , MailMessage содержащий его, нельзя использовать повторно. Для повторного использования вложения необходимо предоставить поток, в который можно выполнить поиск.

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