Image in body of the Mail C# - c#

I want to send the image in the body of the mail. Here, I am loading a chart based on the database records. I converted the chart into bytes by the following code:
string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
byte[] bytes = Convert.FromBase64String(base64);
Now, I want to convert this bytes array into Image and to add the image in the body of the mail.
This is my send mail code:
MailMessage message = new MailMessage();
string fromEmail = "domain.com";
string fromPW = "12345";
string toEmail = "abcde#gmail.com";
message.From = new MailAddress(fromEmail);
message.To.Add(toEmail);
message.Subject = "Chart Mail";
message.Body = "Hi Team";
message.IsBodyHtml = true;
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
SmtpClient smtpClient = new SmtpClient("domain.com", 1234);
smtpClient.EnableSsl = false;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential(fromEmail, fromPW);
smtpClient.Send(message.From.ToString(), message.To.ToString(), message.Subject, message.Body);
In the above code, I want to convert the bytes to image and need to send in the body of the mail. Please suggest.

There is no need to convert the image into bytes.
All you gotta do is:
string attachmentPath = Environment.CurrentDirectory + #"\test.png";
Attachment inline = new Attachment(attachmentPath);
inline.ContentDisposition.Inline = true;
inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
inline.ContentId = contentID;
inline.ContentType.MediaType = "image/png";
inline.ContentType.Name = Path.GetFileName(attachmentPath);
message.Attachments.Add(inline);
This will show the message in 'Inline' layout and not just as an attached image

Related

The image is not displayed when sent to email

string html = "<img src=data:image/png;base64,i0KGgAD34DtaA..........*>"; //*very long
SensMail(mailaddress,html, System.Text.Encoding.UTF8);
public static void SensMail(string sendTo, string body, System.Text.Encoding enCode)
{
string emailaddress = "mail#gmail.com";
string password = "it's secret";
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient();
mail.From = new MailAddress(sendTo);
mail.To.Add(sendTo);
mail.BodyEncoding = enCode;
mail.IsBodyHtml = true;
mail.Subject = "subject";
mail.Body = body;
SmtpServer.UseDefaultCredentials = false;
NetworkCredential NetworkCred = new NetworkCredential(emailaddress,password);
SmtpServer.Credentials = NetworkCred;
SmtpServer.EnableSsl = true;
SmtpServer.Port = 587;
SmtpServer.Host = "smtp.gmail.com";
SmtpServer.Send(mail);
}
Why is the image not displayed ??
I tried to send to two different email providers, without success.
Is this happening for security reasons?
How can this problem be solved?
In HTML it does work and you see the image.
Outlook doesn't understand base64 images. There are two possible ways:
Upload the image file to any web server and then use the image URL in the HTML body for that image. Be aware, Outlook may block external links (even for images) automatically.
You may add an image file as an attachment and then use the cid prefix for the img tag. See Send inline image in email for more information.

Image not showing in gmail mail body after sending it from asp.net c# net.mail as mail.body

I need to send the qrcode generated from the email to his gmail account. I debugged the code and checked with html visualizer and the qrcode is displaying correctly but cannot see it in gmail message
public void generate_qrcode()
{
try
{
string imgurl;
string code = txtCode.Text;
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(code, QRCodeGenerator.ECCLevel.Q);
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
imgBarCode.Height = 150;
imgBarCode.Width = 150;
using (Bitmap bitMap = qrCode.GetGraphic(20))
{
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
imgurl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
//plBarCode.Controls.Add(imgBarCode);
}
SendMail(imgurl);
}
catch (Exception ex)
{
}
}
public void SendMail(String imgurl)
{
string body = "Hello ,<br /><br />Please find your QRcode below<br /><br /><img src=' " + imgurl + " ' height='100' width='100'/><br/><br/>Thanks...";
SmtpClient Smtp_Server = new SmtpClient();
MailMessage e_mail = new MailMessage();
Smtp_Server.UseDefaultCredentials = false;
Smtp_Server.Credentials = new System.Net.NetworkCredential("samplemail527#gmail.com", "Sample527");
Smtp_Server.Port = 587;
Smtp_Server.EnableSsl = true;
Smtp_Server.Host = "smtp.gmail.com";
e_mail = new MailMessage();
e_mail.From = new MailAddress("samplemail527#gmail.com");
e_mail.To.Add(txtCode.Text);
e_mail.Subject = "Email Sending";
e_mail.IsBodyHtml = true;
e_mail.Body = body;
Smtp_Server.Send(e_mail);
}
Base64 images are currently not supported by most email readers. Very unfortunate. You'll need to generate an actual image and attach it to the message with a unique id (like a GUID) and then use that ID as the image tag's src along with the CID prefix.
<img src="cid:GeneratedUniqueId" alt="Your QR Code" />
Here is the good reference to embed image in an email.
Send Email with embedded Images
Maybe you should try to use AlternateView. You have to assign an Id to a resource and use that id within HTML <img> tag. The src attribute should address this Id.Like so:
<img src="cid:ResourceId" />
Don't forget to add linked resource to alternate view.
Here is the full code I used:
Byte[] iconBytes = Convert.FromBase64String(#"iVBOR IMAGE BYTES Hy4vAAN==");
System.IO.MemoryStream iconBitmap = new System.IO.MemoryStream(iconBytes);
LinkedResource iconResource = new LinkedResource(iconBitmap, MediaTypeNames.Image.Jpeg);
iconResource.ContentId = "Icon";
MailMessage msg = new MailMessage();
msg.IsBodyHtml = true;
msg.To.Add(new MailAddress("recipient#domain.com", "Recipient Name"));
msg.From = new MailAddress("sender#domain.com", "Sender Name");
msg.Subject = "Attach image to mail";
string htmlBody = #"<html><head>";
htmlBody += #"<style>";
htmlBody += #"body{ font-family:'Calibri',sans-serif; }";
htmlBody += #"</style>";
htmlBody += #"</head><body>";
htmlBody += #"<h1>The attached image is here below</h1>";
htmlBody += #"<img src='cid:" + iconResource.ContentId + #"'/>";
htmlBody += #"</body></html>";
AlternateView alternativeView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
alternativeView.LinkedResources.Add(iconResource);
msg.AlternateViews.Add(alternativeView);
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = true;
client.Port = 25; // You can use Port 25 if 587 is blocked
client.Host = "smtp.yourhost.com";
client.Send(msg);

I want to email the screenshot in tabular format stored in my local using C#?

I want to automate my work by sending the screenshot taken during automation in tabular email format . I had successfully attached as document, but I want it in tabular format. This is code what I had already tried
public static void email_send() {
string htmlBody = "<html><body><h1>Picture</h1><br><img src=\"cid:test1.jpeg\"></body></html>";
AlternateView avHtml = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
LinkedResource inline = new LinkedResource("test1.jpeg", MediaTypeNames.Image.Jpeg);
inline.ContentId = Guid.NewGuid().ToString();
avHtml.LinkedResources.Add(inline);
Attachment att = new Attachment(#"D:/test123.png");
att.ContentDisposition.Inline = true;
MailMessage mail = new MailMessage();
mail.AlternateViews.Add(avHtml);
System.Net.Mail.SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("*****");
mail.To.Add("*******");
mail.Subject = "Test Mail - 1";
mail.Body = String.Format(
"<h3>Client: " + " Has Sent You A Screenshot</h3>" +
#"<img src=""cid:{0}"" />", inline.ContentId);
mail.IsBodyHtml = true;
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("******", "******");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
You have missed the attachment.
Your linked resource also needs to be attached to the email. You need to add the following code:
mail.Attachments.Add(att);

Error "A recipient must be specified" occurred while sending mail in c#

I am trying to send mail with multiple attachment in c# but I am getting this error
A recipient must be specified while sending mail
Here is my code for sending mail with attachment
string to = txtto.Text; //To address
string from = "xxx#mail.com"; //From address
MailMessage message = new MailMessage();
message.From = new MailAddress(from);
if (fileuploading.HasFile)//Attaching document
{
string FileNamess = fileuploading.PostedFile.FileName;
string FileName = Path.GetFileName(fileuploading.PostedFile.FileName);
message.Attachments.Add(new System.Net.Mail.Attachment(fileuploading.PostedFile.InputStream,FileName));
}
string mailbody = editor.Text;
message.Subject = txtsubject.Text;
message.Body = mailbody;
message.BodyEncoding = Encoding.UTF8;
message.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.gmail.com", 587); //Gmail smtp
System.Net.NetworkCredential basicCredential1 = new
System.Net.NetworkCredential("xxx#mail.com","xxxxx");
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = basicCredential1;
try
{
client.Send(message);
}
catch (Exception ex)
{
throw ex;
}
You have an unused string "to". You need to add this string to recipient list message.To.
To do that refer following snippet;
string to = txtto.Text; //To address
string from = "xxx#mail.com"; //From address
MailMessage message = new MailMessage();
message.From = new MailAddress(from);
message.To.Add(to); //Add this line to your code
For above example to work, your string to should contain a recipient address in format "xxx#mail.com".

Edit HTML Email template at run time in .net code

I below code is to send email by reading the template html, and it works fine. But now my question is how to pass Salutation customerName from my .net code to the template at run time.
StringBuilder strBlr = new StringBuilder();
string strHTML = string.Empty;
string strTempalteHtmlpath = string.Empty;
//create the mail message
MailMessage mail;
string strFrom = ConfigurationSettings.AppSettings["fromAddressForBT"];
string strSubject = "Thanks for choosing Email contact preference";
mail = new MailMessage(strFrom, customerDetails.EmailId);
mail.Subject = strSubject;
//Read Html Template File Path
strTempalteHtmlpath = Convert.ToString(ConfigurationSettings.AppSettings["TemplatePath"]);
strHTML = File.ReadAllText(strTempalteHtmlpath);
strBlr = strBlr.Append(strHTML);
mail.Body = strBlr.ToString();
mail.IsBodyHtml = true;
//first we create the Plain Text part
AlternateView plainView = AlternateView.CreateAlternateViewFromString(strBlr.ToString(), null, "text/plain");
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(strBlr.ToString(), null, "text/html");
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);
//send the message
SmtpClient smtpMail = new SmtpClient(ConfigurationSettings.AppSettings["smtpClient"]);
smtpMail.Send(mail);
mail.Dispose();
Thanks.
This is code for sendemail button
StreamReader sr = new StreamReader(Server.MapPath("Sendpage.htm"));
string body = sr.ReadToEnd();
sr.Close();
body = body.Replace("#NameFamily#", txtNameFamily.Text);
body = body.Replace("#Email#", txtEmail.Text);
body = body.Replace("#Tellphone#", txtTellphone.Text);
body = body.Replace("#Text#", txtText.Text);
body = body.Replace("#Date#", DateTime.Now);
string Time = Convert.ToString(DateTime.Now.ToShortTimeString());
body = body.Replace("#Time#", Time);
SendMail("email that you want to send to it", body);
this is sendmail function code:
private void SendMail(string To, string Body)
{
SmtpClient Mailing = new SmtpClient("mail.domain.com");
MailMessage Message = new MailMessage();
Message.From = new MailAddress("mail#domain.com", "Your name or company name");
Message.Subject = "Subject";
Message.SubjectEncoding = Encoding.UTF8;
Message.IsBodyHtml = true;
Message.BodyEncoding = Encoding.UTF8;
Message.Body = Body;
Message.To.Add(new MailAddress(To));
Mailing.UseDefaultCredentials = false;
NetworkCredential MyCredential = new NetworkCredential("mail#domain.com", "password");
Mailing.Credentials = MyCredential; Mailing.Send(Message);
}

Categories

Resources