In this article I will explain with an example, how attach file from Stream in MailKit using C# and VB.Net.
 
 
Installing MailKit package
You will need to install the MailKit package, for details on installation please refer Install MailKit from Nuget in Visual Studio.
 
 
Attaching File from Stream to MailKit MimeMessage
In order to attach file from Stream in email, a BodyBuilder class object is created.
Then, the name of the File and the InputStream is read from the FileUpload control and are added as attachment to the BodyBuilder class object.
Note: In case you need complete reference, please refer Send Email using MailKit using C# and VB.Net.
 
C#
BodyBuilder builder = new BodyBuilder();
if (fuAttachment.PostedFile.ContentLength > 0)
{
    //Read the name of the File from FileUpload control.
    string fileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
 
    //Read the file stream from FileUpload control.
    Stream stream = fuAttachment.PostedFile.InputStream;
 
    //Attach file stream as attachment.
    builder.Attachments.Add(fileName, stream);
}
 
VB.Net
Dim builder As BodyBuilder = New BodyBuilder()
If fuAttachment.PostedFile.ContentLength > 0 Then
    'Read the name of the File from FileUpload control.
    Dim fileName As String = Path.GetFileName(fuAttachment.PostedFile.FileName)
 
    'Read the file stream from FileUpload control.
    Dim stream As Stream = fuAttachment.PostedFile.InputStream
 
    'Attach file stream as attachment.
    builder.Attachments.Add(fileName, stream)
End If