In this article I will explain with an example, how to attach byte array as attachment 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 Byte Array to MailKit MimeMessage
In order to attach file from BYTE Array in email, a BodyBuilder class object is created.
Then, the name of the File and the InputStream is read from the FileUpload control.
The File Stream is converted to BYTE Array and is read using ReadBytes method of the BinaryReader class.
Finally, the File Name along with the BYTE Array is 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 (postedFile.ContentLength > 0)
{
    //Read the name of the File from FileUpload control.
    string fileName = Path.GetFileName(postedFile.FileName);
 
    //Read the file stream from FileUpload control.
    Stream fs = postedFile.InputStream;
 
    //Convert the stream to byte array.
    BinaryReader br = new BinaryReader(fs);
    byte[] bytes = br.ReadBytes((Int32)fs.Length);
 
    //Attach file byte array as attachment.
    builder.Attachments.Add(fileName, bytes);
}
 
VB.Net
Dim builder As BodyBuilder = New BodyBuilder()
If postedFile.ContentLength > 0 Then
    'Read the name of the File from FileUpload control.
    Dim fileName As String = Path.GetFileName(postedFile.FileName)
 
    'Read the file stream from FileUpload control.
    Dim fs As Stream = postedFile.InputStream
 
    'Convert the stream to byte array.
    Dim br As BinaryReader = New BinaryReader(fs)
    Dim bytes As Byte() = br.ReadBytes(CType(fs.Length, Int32))
 
    'Attach file byte array as attachment.
    builder.Attachments.Add(fileName, bytes)
End If