How to send base64 in email attachment?
First you need to clear your base64 if it start with data:image/png;base64,
. Also you need to remove spaces. The below code fuction for cleaning Base64
public static string Cleaning(string img)
{
var Base64 = img.Split(',')[1];
StringBuilder sb = new StringBuilder(Base64, Base64.Length);
sb.Replace("\r\n", string.Empty);
sb.Replace(" ", string.Empty);
return sb.ToString();
}
Second in send email function you must add your Base64 to MemoryStream.
string fileName = "MyImg.png";
Byte[] bytes = Convert.FromBase64String(Cleaning(Base64)); // clean Base64 then convert it
MemoryStream ms = new MemoryStream(bytes); // create MemoryStrem
Attachment data = new Attachment(ms, fileName); // create Attachment object + add Stream with filename
data.ContentId = fileName;
data.ContentDisposition.Inline = true;
message.Attachments.Add(data); // add data to the attachment
The final code will be like this:
public static string Cleaning(string img)
{
var Base64 = img.Split(',')[1];
StringBuilder sb = new StringBuilder(Base64, Base64.Length);
sb.Replace("\r\n", string.Empty);
sb.Replace(" ", string.Empty);
return sb.ToString();
}
public static void SendEmail(string ToMail, string Base64)
{
MailMessage message = new MailMessage();
SmtpClient smtp = new SmtpClient();
message.From = new MailAddress("info@outlook.com");
message.To.Add(new MailAddress(ToMail));
message.Subject = "Test from C#";
// Here is the sloution!
string fileName = "MyImg.png";
Byte[] bytes = Convert.FromBase64String(Cleaning(Base64));
MemoryStream ms = new MemoryStream(bytes);
Attachment data = new Attachment(ms, fileName);
data.ContentId = fileName;
data.ContentDisposition.Inline = true;
message.Attachments.Add(data);
message.IsBodyHtml = true;
message.Body = "<b>My body</b>";
smtp.Port = 25;
smtp.Host = "mail@outlook.com";
smtp.EnableSsl = false;
smtp.UseDefaultCredentials = false;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(message);
}