Attachment Constructores
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Inicializa una nueva instancia de la clase Attachment.
Sobrecargas
Attachment(String) |
Inicializa una nueva instancia de la clase Attachment con la cadena de contenido especificada. |
Attachment(Stream, ContentType) |
Inicializa una nueva instancia de la clase Attachment con la cadena y el tipo de contenido especificados. |
Attachment(Stream, String) |
Inicializa una nueva instancia de la clase Attachment con la secuencia y el nombre especificados. |
Attachment(String, ContentType) |
Inicializa una nueva instancia de la clase Attachment con la cadena de contenido y el objeto ContentType que se hayan especificado. |
Attachment(String, String) |
Inicializa una nueva instancia de la clase Attachment con la cadena de contenido y la información de tipo MIME que se hayan especificado. |
Attachment(Stream, String, String) |
Inicializa una nueva instancia de la clase Attachment con la cadena, el nombre y la información de tipo MIME que se hayan especificado. |
Attachment(String)
- Source:
- Attachment.cs
- Source:
- Attachment.cs
- Source:
- Attachment.cs
Inicializa una nueva instancia de la clase Attachment con la cadena de contenido 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
Objeto String que contiene una ruta de acceso al archivo que se va a utilizar para crear estos datos adjuntos.
Excepciones
fileName
es null
.
fileName
está vacía.
Ejemplos
En el ejemplo de código siguiente se muestra cómo llamar a este constructor.
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();
}
Comentarios
Las propiedades se establecen de la siguiente manera:
Propiedad. | Valor |
---|---|
MediaType | Plain. |
TransferEncoding | QuotedPrintable. |
Se aplica a
Attachment(Stream, ContentType)
- Source:
- Attachment.cs
- Source:
- Attachment.cs
- Source:
- Attachment.cs
Inicializa una nueva instancia de la clase Attachment con la cadena y el tipo de contenido 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
- contentType
- ContentType
Objeto ContentType que describe los datos de contentStream
.
Excepciones
Ejemplos
En el ejemplo de código siguiente se muestra cómo llamar a este constructor.
// 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();
}
Comentarios
La propiedad TransferEncoding está establecida en Base64.
Si la propiedad de CanSeek la secuencia es false
, los datos adjuntos y el MailMessage que lo contiene no son reutilizables. Debe proporcionar una secuencia que se pueda buscar para reutilizar los datos adjuntos.
Se aplica a
Attachment(Stream, String)
- Source:
- Attachment.cs
- Source:
- Attachment.cs
- Source:
- Attachment.cs
Inicializa una nueva instancia de la clase Attachment con la secuencia y el nombre especificados.
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)
Parámetros
- name
- String
Objeto String que contiene el valor de la propiedad Name del objeto ContentType asociado a estos datos adjuntos. Este valor puede ser null
.
Excepciones
contentStream
es null
.
Ejemplos
En el ejemplo de código siguiente se muestra cómo llamar a este constructor.
// 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;
}
Comentarios
Si name
no null
es o igual a String.Empty (""), el ContentType objeto de estos datos adjuntos se construye con la Name propiedad establecida name
en . La propiedad TransferEncoding está establecida en Base64.
Si la propiedad de CanSeek la secuencia es false
, los datos adjuntos y el MailMessage que lo contiene no son reutilizables. Debe proporcionar una secuencia que se pueda buscar para reutilizar los datos adjuntos.
Se aplica a
Attachment(String, ContentType)
- Source:
- Attachment.cs
- Source:
- Attachment.cs
- Source:
- Attachment.cs
Inicializa una nueva instancia de la clase Attachment con la cadena de contenido y el objeto ContentType que se hayan especificado.
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
Objeto String que contiene una ruta de acceso al archivo que se va a utilizar para crear estos datos adjuntos.
- contentType
- ContentType
Objeto ContentType que describe los datos de fileName
.
Excepciones
fileName
es null
.
mediaType
no tiene el formato correcto.
Se aplica a
Attachment(String, String)
- Source:
- Attachment.cs
- Source:
- Attachment.cs
- Source:
- Attachment.cs
Inicializa una nueva instancia de la clase Attachment con la cadena de contenido y la información de tipo MIME que se hayan especificado.
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)
Parámetros
- mediaType
- String
Objeto String que contiene la información Content-Header MIME de estos datos adjuntos. Este valor puede ser null
.
Excepciones
fileName
es null
.
mediaType
no tiene el formato correcto.
Ejemplos
En el ejemplo de código siguiente se muestra cómo llamar a este constructor.
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();
}
Comentarios
Si mediaType
es null
o igual a String.Empty (""), la MediaType propiedad de estos datos adjuntos se establece en Plain. Si mediaType
no null
es y no es una cadena de longitud cero, se usa para construir el ContentType asociado a estos datos adjuntos.
Se aplica a
Attachment(Stream, String, String)
- Source:
- Attachment.cs
- Source:
- Attachment.cs
- Source:
- Attachment.cs
Inicializa una nueva instancia de la clase Attachment con la cadena, el nombre y la información de tipo MIME que se hayan especificado.
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)
Parámetros
- name
- String
Objeto String que contiene el valor de la propiedad Name del objeto ContentType asociado a estos datos adjuntos. Este valor puede ser null
.
- mediaType
- String
Objeto String que contiene la información Content-Header MIME de estos datos adjuntos. Este valor puede ser null
.
Excepciones
stream
es null
.
mediaType
no tiene el formato correcto.
Ejemplos
En el ejemplo de código siguiente se muestra cómo llamar a este constructor.
// 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();
}
Comentarios
Si mediaType
no null
es o igual a String.Empty (""), se usa para construir la ContentType clase asociada a estos datos adjuntos.
Si mediaType
y name
ambos contienen Name información, se usa el valor especificado en name
. La propiedad TransferEncoding está establecida en Base64.
Si la propiedad de CanSeek la secuencia es false
, los datos adjuntos y el MailMessage que lo contiene no son reutilizables. Debe proporcionar una secuencia que se pueda buscar para reutilizar los datos adjuntos.