Send inline image in email
Try this
string htmlBody = "<html><body><h1>Picture</h1><br><img src=\"cid:filename\"></body></html>";
AlternateView avHtml = AlternateView.CreateAlternateViewFromString
(htmlBody, null, MediaTypeNames.Text.Html);
LinkedResource inline = new LinkedResource("filename.jpg", MediaTypeNames.Image.Jpeg);
inline.ContentId = Guid.NewGuid().ToString();
avHtml.LinkedResources.Add(inline);
MailMessage mail = new MailMessage();
mail.AlternateViews.Add(avHtml);
Attachment att = new Attachment(filePath);
att.ContentDisposition.Inline = true;
mail.From = from_email;
mail.To.Add(data.email);
mail.Subject = "Client: " + data.client_id + " Has Sent You A Screenshot";
mail.Body = String.Format(
"<h3>Client: " + data.client_id + " Has Sent You A Screenshot</h3>" +
@"<img src=""cid:{0}"" />", att.ContentId);
mail.IsBodyHtml = true;
mail.Attachments.Add(att);
C# sending mails with images inline using SmtpClient
One solution that is often mentioned is to add the image as an Attachment
to the mail, and then reference it in the HTML mailbody using a cid:
reference.
However if you use the LinkedResources
collection instead, the inline images will still appear just fine, but don't show as additional attachments to the mail. That's what we want to happen, so that's what I do here:
using (var client = new SmtpClient())
{
MailMessage newMail = new MailMessage();
newMail.To.Add(new MailAddress("you@your.address"));
newMail.Subject = "Test Subject";
newMail.IsBodyHtml = true;
var inlineLogo = new LinkedResource(Server.MapPath("~/Path/To/YourImage.png"), "image/png");
inlineLogo.ContentId = Guid.NewGuid().ToString();
string body = string.Format(@"
<p>Lorum Ipsum Blah Blah</p>
<img src=""cid:{0}"" />
<p>Lorum Ipsum Blah Blah</p>
", inlineLogo.ContentId);
var view = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
view.LinkedResources.Add(inlineLogo);
newMail.AlternateViews.Add(view);
client.Send(newMail);
}
NOTE: This solution adds an AlternateView
to your MailMessage
of type text/html
. For completeness, you should also add an AlternateView
of type text/plain
, containing a plain text version of the email for non-HTML mail clients.
Send e-mail with image on body
You could convert your image to base64 and add that in src or you could just give the page where is the image is located.
Attaching Image in the body of mail in C#
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);
reference: Send an Email in C# with Inline attachments
Adding Image to System.Net.Mail Message
you need to add them in the email message as CID's/linked resources.
here is some code I have used before which works nicely. I hope this gives you some guidance:
Create an AlternateView
:
AlternateView av = AlternateView.CreateAlternateViewFromString(body, null, isHTML ? System.Net.Mime.MediaTypeNames.Text.Html : System.Net.Mime.MediaTypeNames.Text.Plain)
Create a Linked Resource:
LinkedResource logo = new LinkedResource("SomeRandomValue", System.Net.Mime.MediaTypeNames.Image.Jpeg);
logo.ContentId = currentLinkedResource.Key;
logo.ContentType = new System.Net.Mime.ContentType("image/jpg");
// add it to the alternative view
av.LinkedResources.Add(logo);
// finally, add the alternative view to the message:
msg.AlternateView.Add(av);
here is some documentation to help you with what the AlternativeView and LinkedResources are and how it works:
http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/system.net.mail.linkedresource(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/ms144669(v=vs.110).aspx
in the HTML itself, you need to do something like the following:
"<img style=\"width: 157px; height: 60px;\" alt=\"blah blah\" title=\"my title here\" src=\"cid:{0}\" />";
notice the CID followed by a string format {0} - I then use this to replace it with a random value.
UPDATE
To go back and comment on the posters comments... here is the working solution for the poster:
string body = "blah blah blah... body goes here with the image tag: <img src=\"cid:companyLogo\" width="104" height="27" />";
byte[] reader = File.ReadAllBytes("E:\\TestImage.jpg");
MemoryStream image1 = new MemoryStream(reader);
AlternateView av = AlternateView.CreateAlternateViewFromString(body, null, System.Net.Mime.MediaTypeNames.Text.Html);
LinkedResource headerImage = new LinkedResource(image1, System.Net.Mime.MediaTypeNames.Image.Jpeg);
headerImage.ContentId = "companyLogo";
headerImage.ContentType = new ContentType("image/jpg");
av.LinkedResources.Add(headerImage);
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.AlternateViews.Add(av);
message.To.Add(emailTo);
message.Subject = " Your order is being processed...";
message.From = new System.Net.Mail.MailAddress("xxx@example.com");
ContentType mimeType = new System.Net.Mime.ContentType("text/html");
AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
message.AlternateViews.Add(alternate);
// then send message!
how to send email with multiple embedded images with asp.net 4.0 with c#
class Program
{
static void Main(string[] args)
{
SmtpMail oMail = new SmtpMail("TryIt");
SmtpClient oSmtp = new SmtpClient();
// Set sender email address, please change it to yours
oMail.From = "test@emailarchitect.net";
// Set recipient email address, please change it to yours
oMail.To = "support@emailarchitect.net";
// Set email subject
oMail.Subject = "test html email with attachment";
// Your SMTP server address
SmtpServer oServer = new SmtpServer("smtp.emailarchitect.net");
// User and password for ESMTP authentication, if your server doesn't require
// User authentication, please remove the following codes.
oServer.User = "test@emailarchitect.net";
oServer.Password = "testpassword";
// If your SMTP server requires SSL connection, please add this line
// oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
try
{
// Import html body and also import linked image as embedded images.
oMail.ImportHtml( "<html><body>test <img src=\"test.gif\"> importhtml</body></html>",
"c:\\my picture", //test.gif is in c:\\my picture
ImportHtmlBodyOptions.ImportLocalPictures | ImportHtmlBodyOptions.ImportCss );
Console.WriteLine("start to send email with embedded image...");
oSmtp.SendMail(oServer, oMail);
Console.WriteLine("email was sent successfully!");
}
catch (Exception ep)
{
Console.WriteLine("failed to send email with the following error:");
Console.WriteLine(ep.Message);
}
}
}
}
Related Topics
Suppressing "Is Never Used" and "Is Never Assigned To" Warnings in C#
How Much Memory Does a C#/.Net Object Use
How to Use Use Late Binding to Get Excel Instance
Tabcontrol with Close and Add Button
Are There Any Suggestions for Developing a C# Coding Standards/Best Practices Document
How to Read Values from the Querystring with ASP.NET Core
How to Compare Only Date Without Time in Datetime Types in Linq to SQL with Entity Framework
What Is Relation Between Gc, Finalize() and Dispose
Get Image Orientation and Rotate as Per Orientation
Fastest Way to Convert Image to Byte Array
How to Draw Directly on the Windows Desktop, C#
How to Capture a 0..1 to 0..1 Relationship in Entity Framework
How to Set Timer Resolution from C# to 1 Ms
What Are the Benefits of Using C# VS F# or F# VS C#
Pass Parameter to Eventhandler