I am trying to retrieve a QR code image path that is in binary form from a SQL database, then insert that as a full image into the email using MailMessage
and SmtpClient
.
I understand that we would have to convert the base 64
string into an image file, so that it can be visualized.
But I am currently having no clues as to how to do this. Is there any simple explanation or coding examples that I can refer to?
Below is my code for retrieving the QR code image path from the SQL database
//retrieve QR Code image
string getQRimage = "SELECT QRCode FROM Parcel WHERE ConsignmentNum =@num";
SqlCommand cmdGetQR = new SqlCommand(getQRimage, conn);
cmdGetQR.Parameters.AddWithValue("@num", txtConsignmentNum.Text);
SqlDataReader dr1 = cmdGetQR.ExecuteReader();
bool recordFound1 = dr1.Read();
if (recordFound1)
{
byte[] bytes = (byte[])cmdGetQR.ExecuteScalar();
string strBase64 = Convert.ToBase64String(bytes);
Image1.ImageUrl = "data:Image/png;base64," + strBase64;
}
What I am trying to do is to send Image1
in the email body. The coding for the email is as below:
//send email
try
{
//retrieve student email
if (conn.State == System.Data.ConnectionState.Closed)
{
conn.Open();
string getEmail = "SELECT Email FROM Student WHERE StudentID='" + txtStudentID.Text + "'";
SqlCommand cmdGetMail = new SqlCommand(getEmail, conn);
cmdGetMail.Parameters.AddWithValue("@StudentID", txtStudentID.Text);
SqlDataReader dr = cmdGetMail.ExecuteReader();
bool recordFound = dr.Read();
if (recordFound)
{
lblStudentEmail.Text = dr["Email"].ToString();
lblStudentName.Text = dr["StudentName"].ToString();
}
}
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress("contact.now.testing@gmail.com");
mailMessage.To.Add(lblStudentEmail.Text);
mailMessage.IsBodyHtml = true;
mailMessage.Subject = "Parcel" + txtConsignmentNum.Text + "Available for Pick Up";
mailMessage.Body = "Hi " + "sample text" + Image1;
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.EnableSsl = true;
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new System.Net.NetworkCredential("email", "password");
smtpClient.Send(mailMessage);
Response.Write("<script>alert('Your email has been sent!')</script>");
}
catch (Exception ex)
{
throw;
// Response.Write("<script>alert('Your email could not be sent successfully due to error found: " + ex.ToString() + "')</script>");
}
Please let me know if there is any solution or suggestion to this.