SendGrid Image Email - c#

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 + "\" />";

Related

Embedding Multiple Images in Email Displays only Last Image C#

I need to embed 5 links in a row with images in a MailMessage using C#. The problem is only the last embedded image displays in the email. The result I need is this:
Here is what displays in the delivered email:
Here is my code:
public void SendMail()
{
MailMessage mail = new MailMessage();
mail.IsBodyHtml = true;
mail.AlternateViews.Add(GetEmbeddedImage(images));
......
}
private AlternateView GetEmbeddedImage(List<string> images)
{
AlternateView alternateView = null;
string body = "";
string link = #"<a href='http://localhost:55148/Support/Management/Index'>";
for (int i = 0; i < images.Count; i++)
{
string filepath = images[i];
LinkedResource res = new LinkedResource(filepath, MediaTypeNames.Image.Jpeg);
res.ContentId = Guid.NewGuid().ToString();
body = body + link + #"<img src='cid:" + res.ContentId + #"'/></a>";
alternateView = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
alternateView.LinkedResources.Add(res);
}
return alternateView;
}
I figured it out. I don't know why it made a difference, but I collected the LinkedResources into a list and then added them using a foreach:
AlternateView alternateView = null;
string body = "";
string link = #"<a href='http://localhost:55148/Support/Management/Index'>";
List<LinkedResource> resources = new List<LinkedResource>();
for (int i = 0; i < images.Count; i++)
{
string filepath = images[i];
LinkedResource res = new LinkedResource(filepath, MediaTypeNames.Image.Jpeg);
res.ContentId = Guid.NewGuid().ToString();
body = body + link + #"<img src='cid:" + res.ContentId + #"'/></a>";
alternateView = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
resources.Add(res);
}
foreach(LinkedResource r in resources)
{
alternateView.LinkedResources.Add(r);
}
return alternateView;

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.

How to send email using GMAIL API having HTML body + attachment in ASP.NET

var msg = new AE.Net.Mail.MailMessage
{
Subject = subject,
Body = bodyhtml,
From = new System.Net.Mail.MailAddress("myemail")
};
foreach (string add in vendorEmailList.Split(','))
{
if (string.IsNullOrEmpty(add))
continue;
msg.To.Add(new System.Net.Mail.MailAddress(add));
}
msg.ReplyTo.Add(msg.From); // Bounces without this!!
msg.ContentType = "text/html";
////attachment code
foreach (string path in attachments)
{
var bytes = File.ReadAllBytes(path);
string mimeType = MimeMapping.GetMimeMapping(path);
AE.Net.Mail.Attachment attachment = new AE.Net.Mail.Attachment(bytes, mimeType, Path.GetFileName(path), true);
msg.Attachments.Add(attachment);
}
////end attachment code
var msgStr = new StringWriter();
msg.Save(msgStr);
Message message = new Message();
message.Raw = Base64UrlEncode(msgStr.ToString());
var result = gmailService.Users.Messages.Send(message, "me").Execute();
This code is working without attachment but with attachment instead of attachment directly byte[] is appearing in inbox.
If i remove msg.ContentType = "text/html" this line then it is working but html not rendering in email, appearing as plain text.
I want to send both HTML body and attachment, Please help.
MailMessage mail = new MailMessage();
mail.Subject = subject;
mail.Body = bodyhtml;
mail.From = new MailAddress("myemail");
mail.IsBodyHtml = true;
foreach (string add in vendorEmailList.Split(','))
{
if (string.IsNullOrEmpty(add))
continue;
mail.To.Add(new MailAddress(add));
}
foreach (string add in userEmailList.Split(','))
{
if (string.IsNullOrEmpty(add))
continue;
mail.CC.Add(new MailAddress(add));
}
foreach (string path in attachments)
{
//var bytes = File.ReadAllBytes(path);
//string mimeType = MimeMapping.GetMimeMapping(path);
Attachment attachment = new Attachment(path);//bytes, mimeType, Path.GetFileName(path), true);
mail.Attachments.Add(attachment);
}
MimeKit.MimeMessage mimeMessage = MimeMessage.CreateFromMailMessage(mail);
Message message = new Message();
message.Raw = Base64UrlEncode(mimeMessage.ToString());
var result = gmailService.Users.Messages.Send(message, "me").Execute();
I found solution after lot of efforts. Instead of AE.Net.Mail.MailMessage used System.Net.Mail.MailMessage and MimeKit to convert it to raw string. And now html body with attachment is working fine.
try adding IsBodyHtml = true
new AE.Net.Mail.MailMessage
{
Subject = subject,
Body = bodyhtml,
From = new System.Net.Mail.MailAddress("myemail")
IsBodyHtml = true
};

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);
}

C# LinkedResource using base64 string

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);

Categories