Attachment Construtores

Definição

Inicializa uma nova instância da Attachment classe.

Sobrecargas

Name Description
Attachment(String)

Inicializa uma nova instância da Attachment classe com a cadeia de conteúdo especificada.

Attachment(Stream, ContentType)

Inicializa uma nova instância da Attachment classe com o fluxo e o tipo de conteúdo especificados.

Attachment(Stream, String)

Inicializa uma nova instância da Attachment classe com o fluxo e nome especificados.

Attachment(String, ContentType)

Inicializa uma nova instância da Attachment classe com a cadeia de conteúdo especificada e ContentType.

Attachment(String, String)

Inicializa uma nova instância da Attachment classe com a string de conteúdo especificada e a informação do tipo MIME.

Attachment(Stream, String, String)

Inicializa uma nova instância da Attachment classe com o fluxo especificado, nome e informação do tipo MIME.

Attachment(String)

Inicializa uma nova instância da Attachment classe com a cadeia de conteúdo especificada.

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)

Parâmetros

fileName
String

A String que contém um caminho de ficheiro para criar este anexo.

Exceções

fileName é null.

fileName está vazio.

Exemplos

O exemplo de código seguinte demonstra como chamar este construtor.

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();
}

Observações

As propriedades são definidas da seguinte forma:

Property Value
MediaType Plain.
TransferEncoding QuotedPrintable.

Aplica-se a

Attachment(Stream, ContentType)

Inicializa uma nova instância da Attachment classe com o fluxo e o tipo de conteúdo especificados.

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)

Parâmetros

contentStream
Stream

Um livro Stream legível que contém o conteúdo deste anexo.

contentType
ContentType

A ContentType que descreve os dados em contentStream.

Exceções

contentType é null.

-ou-

contentStream é null.

Exemplos

O exemplo de código seguinte demonstra como chamar este construtor.

// 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();
}

Observações

A propriedade TransferEncoding está definida como Base64.

Se a propriedade do CanSeek fluxo for false, o anexo e o MailMessage que o contém não são reutilizáveis. Deve fornecer um fluxo que possa ser pesquisado para reutilizar um anexo.

Aplica-se a

Attachment(Stream, String)

Inicializa uma nova instância da Attachment classe com o fluxo e nome especificados.

public:
 Attachment(System::IO::Stream ^ contentStream, System::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)

Parâmetros

contentStream
Stream

Um livro Stream legível que contém o conteúdo deste anexo.

name
String

A String que contém o valor da Name propriedade do ContentType associado a este anexo. Este valor pode ser null.

Exceções

contentStream é null.

Exemplos

O exemplo de código seguinte demonstra como chamar este construtor.

// 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;
}

Observações

Se name não null for ou for igual a String.Empty (""), o ContentType para este anexo é construído com a Name propriedade definida em name. A propriedade TransferEncoding está definida como Base64.

Se a propriedade do CanSeek fluxo for false, o anexo e o MailMessage que o contém não são reutilizáveis. Deve fornecer um fluxo que possa ser pesquisado para reutilizar um anexo.

Aplica-se a

Attachment(String, ContentType)

Inicializa uma nova instância da Attachment classe com a cadeia de conteúdo especificada e 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)

Parâmetros

fileName
String

A String que contém um caminho de ficheiro para criar este anexo.

contentType
ContentType

A ContentType que descreve os dados em fileName.

Exceções

fileName é null.

contentType não está no formato correto.

Aplica-se a

Attachment(String, String)

Inicializa uma nova instância da Attachment classe com a string de conteúdo especificada e a informação do tipo MIME.

public:
 Attachment(System::String ^ fileName, System::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)

Parâmetros

fileName
String

A String que contém o conteúdo deste anexo.

mediaType
String

A String que contém a informação do Cabeçalho de Conteúdo MIME para este anexo. Este valor pode ser null.

Exceções

fileName é null.

mediaType não está no formato correto.

Exemplos

O exemplo de código seguinte demonstra como chamar este construtor.

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();
}

Observações

Se mediaType for igual a String.Empty (""), a MediaType propriedade para este anexo é definida como Plainnull . Se mediaType não null for e não for uma corda de comprimento zero, é usada para construir o ContentType associado a esta ligação.

Aplica-se a

Attachment(Stream, String, String)

Inicializa uma nova instância da Attachment classe com o fluxo especificado, nome e informação do tipo MIME.

public:
 Attachment(System::IO::Stream ^ contentStream, System::String ^ name, System::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)

Parâmetros

contentStream
Stream

Um livro Stream legível que contém o conteúdo deste anexo.

name
String

A String que contém o valor da Name propriedade do ContentType associado a este anexo. Este valor pode ser null.

mediaType
String

A String que contém a informação do Cabeçalho de Conteúdo MIME para este anexo. Este valor pode ser null.

Exceções

contentStream é null.

mediaType não está no formato correto.

Exemplos

O exemplo de código seguinte demonstra como chamar este construtor.

// 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();
}

Observações

Se mediaType não null for ou for igual a String.Empty (""), é usado para construir a ContentType classe associada a este anexo.

Se mediaType e name ambos contêm Name informação, o valor especificado em name é usado. A propriedade TransferEncoding está definida como Base64.

Se a propriedade do CanSeek fluxo for false, o anexo e o MailMessage que o contém não são reutilizáveis. Deve fornecer um fluxo que possa ser pesquisado para reutilizar um anexo.

Aplica-se a