Add mail attachment from filestream
To add a mail attachment from a file stream in C#, you can use the System.Net.Mail.Attachment
class and pass the file stream to the Attachment
constructor. Here's an example:
using System.IO;
using System.Net.Mail;
// assume you have a file stream object called "fileStream"
using (var attachment = new Attachment(fileStream, "attachmentName", "text/plain"))
{
// add the attachment to the mail message
mailMessage.Attachments.Add(attachment);
}
In this example, fileStream
is the file stream object that contains the file you want to attach, attachmentName
is the name of the attachment, and "text/plain"
is the MIME type of the attachment.
You can also specify additional properties, such as the content disposition and the file name, using the Attachment
constructor:
using (var attachment = new Attachment(fileStream, "attachmentName", "text/plain", "inline", "attachment.txt"))
{
// add the attachment to the mail message
mailMessage.Attachments.Add(attachment);
}
In this example, "inline"
specifies the content disposition of the attachment, and "attachment.txt"
is the file name of the attachment.
Make sure to dispose of the file stream object when you're done with it, either by using a using
statement or by calling the Dispose
method explicitly.
Here's a complete example:
using System.IO;
using System.Net.Mail;
// assume you have a file stream object called "fileStream"
using (var attachment = new Attachment(fileStream, "attachmentName", "text/plain"))
{
// create a new mail message
var mailMessage = new MailMessage();
// add the attachment to the mail message
mailMessage.Attachments.Add(attachment);
// set the mail message properties
mailMessage.From = new MailAddress("[email protected]");
mailMessage.To.Add("[email protected]");
mailMessage.Subject = "Test email with attachment";
mailMessage.Body = "This is a test email with an attachment.";
// send the mail message
using (var smtpClient = new SmtpClient())
{
smtpClient.Send(mailMessage);
}
}
This example creates a new mail message, adds the attachment to the message, sets the mail message properties, and sends the message using an SmtpClient
object.