C# LinkedResource using base64 string - c#

How can I put this ==>
url('data:image/jpeg;base64,/9j/4AAQSkZJRgABAgEASABIAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB') into new System.Net.Mail.LinkedResource()
to send mail form C#, using background css style with base64 string, not file url.

I wondered this myself and got to this post. I solved it and figured i would share the my solution.
var imageData = Convert.FromBase64String("/9j/4AAQSkZJRgABAgEASABIAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB");
var contentId = Guid.NewGuid().ToString();
var linkedResource = new LinkedResource(new MemoryStream(imageData), "image/jpeg");
linkedResource.ContentId = contentId;
linkedResource.TransferEncoding = TransferEncoding.Base64;
var body = string.Format("<img src=\"cid:{0}\" />", contentId);
var htmlView = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
htmlView.LinkedResources.Add(linkedResource);

Related

SendGrid Image Email

I am trying to send an email via Sendgrid using the following code. The email has an image which I am trying to send.
var client = new SendGridClient("MYAPIKEY");
var from = new EmailAddress("from#from.com");
var subject = "test";
var to = new EmailAddress("to#to.com");
var plainTextContent = "";
Image s = CreateBitmapImage("Hi");
ImageConverter converter = new ImageConverter();
var imageBytes = (byte[])converter.ConvertTo(s, typeof(byte[]));
var b64String = Convert.ToBase64String(imageBytes);
var dataUrl = "data:image/jpg;base64," + b64String;
var htmlContent = "<img src='" + dataUrl + "' />";
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
var response = client.SendEmailAsync(msg).Result;
Following is what i see in gmail after sending the image.
I referred to sendgrid blogpost for embedding image via base64. Please suggest if I am doing wrong somewhere.
Do you check if you have it set?
MailMessage msg = new MailMessage();
msg.IsBodyHtml = true;
msg.BodyEncoding = Encoding.GetEncoding("utf-8");
If you set,you trying
var dataUrl = "";
using (System.Drawing.Image s = CreateBitmapImage("Hi"))
{
ImageConverter converter = new ImageConverter();
var imageBytes = (byte[])converter.ConvertTo(s, typeof(byte[]));
var b64String = Convert.ToBase64String(imageBytes);
dataUrl = "data:image/jpg;base64," + b64String;
}
var htmlContent = "<img src=\"" + dataUrl + "\" />";

Embed c# image into html email

I have a class that returns an Image:
public static Image GenerateVoucher(decimal voucherAmount, string voucherCode,
DateTime expiryDate)
{
...
Image img = Image.FromFile(path);
using (Graphics graphics = Graphics.FromImage(img))
{
...various drawing on the image...
graphics.DrawString(voucherAmount.ToString(), new Font(handleGothic.Families[0], 113), blueBrushColour, largeVoucherAmountLocation);
}
return img;
}
and I want to embed this response into an email:
public static MailMessage CreateImagedEmail(string mailTo, decimal voucherAmount, string voucherCode, DateTime expiryDate)
{
var mail = new MailMessage();
mail.From = new MailAddress("fromaddress.com");
mail.To.Add(mailTo);
mail.Subject = "Your Email with an image inline";
var plainView = AlternateView.CreateAlternateViewFromString(
"Your email client has detected it is unable to render html emails...",
null, "text/plain");
var htmlView = AlternateView.CreateAlternateViewFromString(
"<h1>Some HTML message </h1>" +
"<img src=cid:voucher>",
null, "text/html");
var voucher = GenerateVoucher(voucherAmount, voucherCode, expiryDate);
LinkedResource voucherImg = new LinkedResource(path);
voucherImg.ContentId = "voucher";
htmlView.LinkedResources.Add(voucherImg);
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);
return mail;
}
This works fine in the example above when returning the image from the file system, but when I try and add the Image from the method above the LinkedResources complains that it is not a string. I'm happy to convert it to a stream if that will work

Send an Embed Base64 Image in an email with C# in order to be decoded by gmail

I am trying to send an email which has embedded images in the body of the message.
The images are encoded as Base64 string. The contents looks as follows:
"<p><span>My Name</span></p><img src=\"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEA..." width=\"167\" height=\"167\" />"
The base64 string has been cut off for this example.
I am using the following code to send the html as attachment, However, the image in the example is still been refused to be decoded by the emails providers (gmail/outlook). I do not know if i am not doing it properly.
string htmlBody = "<p><span>My Name</span></p><img src=\"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEA..." width=\"167\" height=\"167\" />";
AlternateView avHtml = AlternateView.CreateAlternateViewFromString
(htmlBody, null, MediaTypeNames.Text.Html);
var mailTo = Config.Debug ? new MailAddress(Config.DebugEmailAddress) : new MailAddress("myemail#gmail.com");
var mailFrom = new MailAddress("myemail#gmail.com");
var mailMessage = new MailMessage(mailFrom, mailTo) { Subject = "hola q tal", Body = "holaaa", IsBodyHtml = true };
mailMessage.To.Add("myemail#gmail.com");
mailMessage.AlternateViews.Add(avHtml);
var sender1 = new SmtpClient
{
Host = Config.SmtpHost,
Port = 25,
Credentials = new NetworkCredential(Config.SmtpHostUserName, Config.SmtpHostPassword)
};
sender1.Send(mailMessage);
I would appreciate any sugesstions.

linked resource does not come as inline image C#

I have written below code to embed image in the mail which is being sent from my c# code. But when i check the mail, i get image like an attachment and not as an inline image. (Gmail)
AlternateView htmlBodyView = null;
string htmlBody = "<html><body><h1></h1><br><img src=\"cid:SampleImage\"></body></html>";
AlternateView plainTextView = AlternateView.CreateAlternateViewFromString(htmlBody, null, "text/html");
ImageConverter ic = new ImageConverter();
Byte[] ba = (Byte[])ic.ConvertTo(bitmap_obj, typeof(Byte[]));
using (MemoryStream logo = new MemoryStream(ba))
{
LinkedResource sampleImage = new LinkedResource(logo, "image/jpeg");
sampleImage.ContentId = "sampleImage";
htmlBodyView.LinkedResources.Add(sampleImage);
p.SendEmail(htmlBodyView);
}
For reference, a full working simplified example:
public void SendMail()
{
LinkedResource logo = new LinkedResource(
"images\\image005.png", //Path of file
"image/png"); //Mime type: Important!
logo.ContentId = "logo"; //ID for reference
//Actual HTML content of the body in an 'AlternateView' object.
AlternateView vw = AlternateView.CreateAlternateViewFromString(
"Hello, this is <b>HTML</b> mail with embedded image: <img src=\"cid:logo\" />",
null,
MediaTypeNames.Text.Html); //Mime type: again important!
vw.LinkedResources.Add(logo);
var msg = new MailMessage() { IsBodyHtml = true };
msg.AlternateViews.Add(vw);
msg.From = new MailAddress("sender#domain.com");
msg.To.Add(new MailAddress("reciever#domain.com"));
msg.Subject = "HTML Mail!";
using (var client = new SmtpClient("localhost", 25))
client.Send(msg);
}

AlternateView and čćžšđ when sending mail by C#

MailMessage message = new MailMessage(email.From,
email.To,
email.Subject,
email.Body);
message.BodyEncoding = Encoding.GetEncoding("utf-8");
string body = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";
body += "<HTML><HEAD><META http-equiv=Content-Type content=\"text/html; charset=utf-8\">";
body += "</HEAD><BODY><DIV>";
body += email.Body.Replace("\r\n", "<br />");
body += "</DIV></BODY></HTML>";
AlternateView plainView = AlternateView.CreateAlternateViewFromString(Regex.Replace(email.Body, #"<(.|\n)*?", string.Empty), null, "text/plain");
message.AlternateViews.Add(plainView);
ContentType mimeType = new ContentType("text/html");
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(email.Body, mimeType);
message.AlternateViews.Add(htmlView);
where email.Body and email.Subject is for example "čžćšđščžčžčšđš"
and when i get mail, Subject is ok but body is corrupted like Äžšđ
Problem is in AlternateView.
here:
ContentType mimeType = new ContentType("text/html");
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(email.Body, mimeType);
message.AlternateViews.Add(htmlView);
what to do?
According to the following question
How do I set Encoding on AlternateView
the answer is to set the content type of the alternate view appropriately. You are passing null as the encoding, consider passing UTF-8 instead:
AlternateView plainView = AlternateView.CreateAlternateViewFromString(
Regex.Replace(email.Body, #"<(.|\n)*?", string.Empty),
Encoding.UTF8, "text/plain");
You're using null for AlternateView encoding in constructor, replace it with Encoding.GetEncoding("utf-8")
Update:
You've updated your question before it was using null in constructor, anyway there is constructor with encoding parameter.

Categories