Hiamar,
Refer below sample code for sending multiple attachment of binary data from database.
C#
protected void SendEmail(object sender, EventArgs e)
{
string to = txtTo.Text;
string from = txtEmail.Text;
string subject = txtSubject.Text;
string body = txtBody.Text;
using (MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text))
{
mm.Subject = txtSubject.Text;
mm.Body = txtBody.Text;
foreach (DataRow dr in GetFileFromDataBase().Rows)
{
mm.Attachments.Add(new Attachment(new MemoryStream((byte[])dr["Data"]), dr["Name"].ToString()));
}
mm.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Email sent.');", true);
}
}
private DataTable GetFileFromDataBase()
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string query = "SELECT * FROM tblFiles";
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
VB.Net
Protected Sub SendEmail(ByVal sender As Object, ByVal e As EventArgs)
Dim [to] As String = txtTo.Text
Dim from As String = txtEmail.Text
Dim subject As String = txtSubject.Text
Dim body As String = txtBody.Text
Using mm As MailMessage = New MailMessage(txtEmail.Text, txtTo.Text)
mm.Subject = txtSubject.Text
mm.Body = txtBody.Text
For Each dr As DataRow In GetFileFromDataBase().Rows
mm.Attachments.Add(New Attachment(New MemoryStream(CType(dr("Data"), Byte())), dr("Name").ToString()))
Next
mm.IsBodyHtml = False
Dim smtp As SmtpClient = New SmtpClient()
smtp.Host = "smtp.gmail.com"
smtp.EnableSsl = True
Dim NetworkCred As NetworkCredential = New NetworkCredential(txtEmail.Text, txtPassword.Text)
smtp.UseDefaultCredentials = True
smtp.Credentials = NetworkCred
smtp.Port = 587
smtp.Send(mm)
ClientScript.RegisterStartupScript(Me.[GetType](), "alert", "alert('Email sent.');", True)
End Using
End Sub
Private Function GetFileFromDataBase() As DataTable
Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim query As String = "SELECT * FROM tblFiles"
Dim cmd As SqlCommand = New SqlCommand(query)
Using con As SqlConnection = New SqlConnection(conString)
Using sda As SqlDataAdapter = New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As DataTable = New DataTable()
sda.Fill(dt)
Return dt
End Using
End Using
End Using
End Function