Why from c# mail want to send picture (signature) in body? - c#

I would like to send mail with a picture inside the email body. In my first attempts, the picture appears like an attachment: it is visible but at the end. I need the picture to be at the center of the email body.
The tutorial which I used is link.
My code looks like this:
mail.Body = "string htmlBody = \"<html><body><h1><center><img src=\"C:\\picture.png\"/></h1></html>";
string contentID = "image1";
Attachment inline = new Attachment("C:\\picture.png");
inline.ContentDisposition.Inline = true;
inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
inline.ContentId = contentID;
inline.ContentType.MediaType = "image/png";
inline.ContentType.Name = "C:\\picture.png";
mail.Attachments.Add(inline);
mail.IsBodyHtml = true;

If you'd really have followed the tutorial, you'd have seen this code:
email.Body = "[...]<img src=\"##IMAGE##\" alt=\"\">";
// generate the contentID string using the datetime
string contentID = Path.GetFileName(attachmentPath).Replace(".", "");
Attachment inline
[...]
inline.ContentId = contentID;
[...]
email.Attachments.Add(inline);
// replace the tag with the correct content ID
email.Body = email.Body.Replace("##IMAGE##", "cid:" + contentID);
Of course using <img src="C:\picture.png"> won't work, since the user that receives the mail most probably won't have that image in that path on their PC, let alone when they're using webmail.

Related

Sending email with inline images with C#, some people can see images, some people can't

In the HTML there are two images:
<IMG SRC="cid:#IMG01#" >
<IMG SRC="cid:#IMG02#" >
The C# code is:
var message = new MailMessage
{
Priority = MailPriority.Normal,
Sender = new MailAddress(utente.Email, "xxx.it"),
From = new MailAddress(utente.Email, "xxx.it")
};
message.To.Add(new MailAddress("xxx#tiscali.it", "aaaaaaaa"));
message.Subject = "xywz";
message.IsBodyHtml = true;
message.Body = Modello;
Attachment AttPrinc = new Attachment(path + "Attachment.pdf");
message.Attachments.Add(AttPrinc);
string contentID1 = "IMMAGINE01";
string contentID2 = "IMMAGINE02";
Modello = Modello.Replace("#IMG01#", contentID1);
Modello = Modello.Replace("#IMG02#", contentID2);
LinkedResource InlineImg01 = new LinkedResource(path + "img01.jpg", "image/jpg");
InlineImg01.ContentId = contentID1;
LinkedResource InlineImg02 = new LinkedResource(path + "img02.jpg", "image/jpg");
InlineImg02.ContentId = contentID2;
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(Modello, null, "text/html");
htmlView.LinkedResources.Add(InlineImg02);
htmlView.LinkedResources.Add(InlineImg01);
message.AlternateViews.Add(htmlView);
var mailClient = new SmtpClient();
mailClient.Send(message);
I send the email and, on my PC with Thunderbird, I see all correct, on my PC with the webmail, I see the images, on my phone (Huawey Mate 8) with webmail, I don't see the images.
I send the email to other persons (tester), and some of them can see the images, some others can't see the images.
I'm going crazy.
Any suggestion?
After long hours of debug, I found the problem: the HTML file was generated by Word ... I rewrote the file from scratch and magically all works well everywhere.
The HTML code generated by Word was something insane, classes and classes, all for a simple document.

set image in email body using html c#

I know that thats not a new question but i want to know that when i set image in my Email Body using the below C# code, why my image not show on mail
SmtpClient client = new SmtpClient();
MailMessage myMessage = new MailMessage();
String Body = "<img src=\"images/logo2.png\" style=\"width:75px; height:75px;\" />";
myMessage.To.Add(new MailAddress(txtemail.Text));
myMessage.Subject = "Subject";
myMessage.Body = Body;
myMessage.IsBodyHtml = true;
try
{
client.Send(myMessage);
}
catch (Exception ex)
{
Response.Write("Unable to send Email" + ex);
}
I am using asp.net c#.
Email will be opened in an email client and doesn't know which web-application to access the image. So your image src shouldn't be relative to the application. Change the src to include the full url:
<img src=\"http://www.somedomain.nl/images/logo2.png\"
Test the url in a browser by taking the src value and try browsing it. If it doesn't work, the src value isn't retrievable.

Email with image via external path C#

Here is a situation.
I am sending an email that has image as html body
<img src="http://www.google.com/images/srpr/logo11w.png" alt="click me" />
After receiving email image src is changed to
<img src="https://bay179.mail.live.com/Handlers/ImageProxy.mvc?bicild=&canary=ei12UmVJE9u9hgMk5TdV12Y1X%2b9Vc365IL%2bmULwd%2bfk%3d0&url=http%3a%2f%2fwww.google.com%2fimages%2fsrpr%2flogo11w.pngf" alt="click me">
Hence does not render image. Following is the code used to send email
SmtpClient sc = new SmtpClient("smtp.live.com");
sc.Port = 587;
sc.UseDefaultCredentials = false;
sc.Credentials = new NetworkCredential("someemail#hotmail.com", "password");
sc.EnableSsl = true;
MailMessage m = new MailMessage();
m.From = new MailAddress("someemail#hotmail.com");
m.Subject = "test subject";
m.IsBodyHtml = true;
m.Body = "<img src=\"http://www.google.com/images/srpr/logo11w.png\" alt=\"click me\" /><img src=\"https://campaign-uploads.s3.amazonaws.com/newsletter/2015/19Apr_wk17/EN/images/logo.jpg\" />";
m.To.Add(new MailAddress("someemail#hotmail.com"));
sc.Send(m);
First image url gets changed and second image's url remains same. So whats the science?
I don't want to embed image.
Once you send the e-mail you have yielded control to the receiving system. Most MTAs are going to do some kind of reformatting either due to anti-virus, phishing, etc. scans. Many will rework the img source to use their own proxies. You have no way to stop them. You just get to work with them.

Send email with img attachment in asp.net to a user with mac mail [duplicate]

sending mail along with embedded image using asp.net
I have already used following but it can't work
Dim EM As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage(txtFrom.Text, txtTo.Text)
Dim A As System.Net.Mail.Attachment = New System.Net.Mail.Attachment(txtImagePath.Text)
Dim RGen As Random = New Random()
A.ContentId = RGen.Next(100000, 9999999).ToString()
EM.Attachments.Add(A)
EM.Subject = txtSubject.Text
EM.Body = "<body>" + txtBody.Text + "<br><img src='cid:" + A.ContentId +"'></body>"
EM.IsBodyHtml = True
Dim SC As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient(txtSMTPServer.Text)
SC.Send(EM)
If you are using .NET 2 or above you can use the AlternateView and LinkedResource classes like this:
string html = #"<html><body><img src=""cid:YourPictureId""></body></html>";
AlternateView altView = AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html);
LinkedResource yourPictureRes = new LinkedResource("yourPicture.jpg", MediaTypeNames.Image.Jpeg);
yourPictureRes.ContentId = "YourPictureId";
altView.LinkedResources.Add(yourPictureRes);
MailMessage mail = new MailMessage();
mail.AlternateViews.Add(altView);
Hopefully you can deduce the VB equivalent.
After searching and trying must be four or five 'answers' I felt I had to share what I finally found to actually work as so many people seem to not know how to do this or some give elaborate answers that so many others have issues with, plus a few do and only give a snippet answer which then has to be interpreted. As I don't have a blog but I'd like to help others here is some full code to do it all. Big thanks to Alex Peck, as it's his answer expanded on.
inMy.aspx asp.net file
<div>
<asp:LinkButton ID="emailTestLnkBtn" runat="server" OnClick="sendHTMLEmail">testemail</asp:LinkButton>
</div>
inMy.aspx.cs code behind c# file
protected void sendHTMLEmail(object s, EventArgs e)
{
/* adapted from http://stackoverflow.com/questions/1113345/sending-mail-along-with-embedded-image-using-asp-net
and http://stackoverflow.com/questions/886728/generating-html-email-body-in-c-sharp */
string myTestReceivingEmail = "yourEmail#address.com"; // your Email address for testing or the person who you are sending the text to.
string subject = "This is the subject line";
string firstName = "John";
string mobileNo = "07711 111111";
// Create the message.
var from = new MailAddress("emailFrom#address.co.uk", "displayed from Name");
var to = new MailAddress(myTestReceivingEmail, "person emailing to's displayed Name");
var mail = new MailMessage(from, to);
mail.Subject = subject;
// Perform replacements on the HTML file (which you're using as a template).
var reader = new StreamReader(#"c:\Temp\HTMLfile.htm");
string body = reader.ReadToEnd().Replace("%TEMPLATE_TOKEN1%", firstName).Replace("%TEMPLATE_TOKEN2%", mobileNo); // and so on as needed...
// replaced this line with imported reader so can use a templete ....
//string html = body; //"<html><body>Text here <br/>- picture here <br /><br /><img src=""cid:SACP_logo_sml.jpg""></body></html>";
// Create an alternate view and add it to the email. Can implement an if statement to decide which view to add //
AlternateView altView = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
// Logo 1 //
string imageSource = (Server.MapPath("") + "\\logo_sml.jpg");
LinkedResource PictureRes = new LinkedResource(imageSource, MediaTypeNames.Image.Jpeg);
PictureRes.ContentId = "logo_sml.jpg";
altView.LinkedResources.Add(PictureRes);
// Logo 2 //
string imageSource2 = (Server.MapPath("") + "\\booking_btn.jpg");
LinkedResource PictureRes2 = new LinkedResource(imageSource2, MediaTypeNames.Image.Jpeg);
PictureRes2.ContentId = "booking_btn.jpg";
altView.LinkedResources.Add(PictureRes2);
mail.AlternateViews.Add(altView);
// Send the email (using Web.Config file to store email Network link, etc.)
SmtpClient mySmtpClient = new SmtpClient();
mySmtpClient.Send(mail);
}
HTMLfile.htm
<html>
<body>
<img src="cid:logo_sml.jpg">
<br />
Hi %TEMPLATE_TOKEN1% .
<br />
<br/>
Your mobile no is %TEMPLATE_TOKEN2%
<br />
<br />
<img src="cid:booking_btn.jpg">
</body>
</html>
in your Web.Config file, inside your < configuration > block you need the following to allow testing in a TempMail folder on your c:\drive
<system.net>
<mailSettings>
<smtp deliveryMethod="SpecifiedPickupDirectory" from="madeupEmail#address.com">
<specifiedPickupDirectory pickupDirectoryLocation="C:\TempMail"/>
</smtp>
</mailSettings>
</system.net>
the only other things you will need at the top of your aspx.cs code behind file are the Using System includes (if I've missed one out you just right click on the unknown class and choose the 'Resolve' option)
using System.Net.Mail;
using System.Text;
using System.Reflection;
using System.Net.Mime; // need for mail message and text encoding
using System.IO;
Hope this helps someone and big thanks to the above poster for giving the answer needed to get the job done (as well as the other link in my code).
It works but im open to improvements.
cheers.
Thanks to the other answers I managed to get this to work - the only difference is the directory of the image - if the image is the same directory as the application than this can be used Ex:Directory.GetCurrentDirectory() + #"\ClientApp\public\img\blur.jpg
public void SendMail(string receiver, string subject, string content)
{
SmtpClient client = new SmtpClient(emailServiceConfig.SmtpServer);
client.EnableSsl = true; // Important ###
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(emailServiceConfig.Username, emailServiceConfig.Password);
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(emailServiceConfig.From);
mailMessage.To.Add(receiver);
//mailMessage.Body = content;
mailMessage.Subject = subject;
//Adding image =============================================
string html = #$"<html><body><img src=""cid:PageScreenshot"">{content}</body></html>";
AlternateView altView = AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html);
LinkedResource screenshotRes = new LinkedResource(Directory.GetCurrentDirectory() + #"\ClientApp\public\img\screeenshot2.jpg", MediaTypeNames.Image.Jpeg);
screenshotRes.ContentId = "PageScreenshot";
altView.LinkedResources.Add(screenshotRes);
mailMessage.AlternateViews.Add(altView);
client.Send(mailMessage);
}

sending mail along with embedded image using asp.net

sending mail along with embedded image using asp.net
I have already used following but it can't work
Dim EM As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage(txtFrom.Text, txtTo.Text)
Dim A As System.Net.Mail.Attachment = New System.Net.Mail.Attachment(txtImagePath.Text)
Dim RGen As Random = New Random()
A.ContentId = RGen.Next(100000, 9999999).ToString()
EM.Attachments.Add(A)
EM.Subject = txtSubject.Text
EM.Body = "<body>" + txtBody.Text + "<br><img src='cid:" + A.ContentId +"'></body>"
EM.IsBodyHtml = True
Dim SC As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient(txtSMTPServer.Text)
SC.Send(EM)
If you are using .NET 2 or above you can use the AlternateView and LinkedResource classes like this:
string html = #"<html><body><img src=""cid:YourPictureId""></body></html>";
AlternateView altView = AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html);
LinkedResource yourPictureRes = new LinkedResource("yourPicture.jpg", MediaTypeNames.Image.Jpeg);
yourPictureRes.ContentId = "YourPictureId";
altView.LinkedResources.Add(yourPictureRes);
MailMessage mail = new MailMessage();
mail.AlternateViews.Add(altView);
Hopefully you can deduce the VB equivalent.
After searching and trying must be four or five 'answers' I felt I had to share what I finally found to actually work as so many people seem to not know how to do this or some give elaborate answers that so many others have issues with, plus a few do and only give a snippet answer which then has to be interpreted. As I don't have a blog but I'd like to help others here is some full code to do it all. Big thanks to Alex Peck, as it's his answer expanded on.
inMy.aspx asp.net file
<div>
<asp:LinkButton ID="emailTestLnkBtn" runat="server" OnClick="sendHTMLEmail">testemail</asp:LinkButton>
</div>
inMy.aspx.cs code behind c# file
protected void sendHTMLEmail(object s, EventArgs e)
{
/* adapted from http://stackoverflow.com/questions/1113345/sending-mail-along-with-embedded-image-using-asp-net
and http://stackoverflow.com/questions/886728/generating-html-email-body-in-c-sharp */
string myTestReceivingEmail = "yourEmail#address.com"; // your Email address for testing or the person who you are sending the text to.
string subject = "This is the subject line";
string firstName = "John";
string mobileNo = "07711 111111";
// Create the message.
var from = new MailAddress("emailFrom#address.co.uk", "displayed from Name");
var to = new MailAddress(myTestReceivingEmail, "person emailing to's displayed Name");
var mail = new MailMessage(from, to);
mail.Subject = subject;
// Perform replacements on the HTML file (which you're using as a template).
var reader = new StreamReader(#"c:\Temp\HTMLfile.htm");
string body = reader.ReadToEnd().Replace("%TEMPLATE_TOKEN1%", firstName).Replace("%TEMPLATE_TOKEN2%", mobileNo); // and so on as needed...
// replaced this line with imported reader so can use a templete ....
//string html = body; //"<html><body>Text here <br/>- picture here <br /><br /><img src=""cid:SACP_logo_sml.jpg""></body></html>";
// Create an alternate view and add it to the email. Can implement an if statement to decide which view to add //
AlternateView altView = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
// Logo 1 //
string imageSource = (Server.MapPath("") + "\\logo_sml.jpg");
LinkedResource PictureRes = new LinkedResource(imageSource, MediaTypeNames.Image.Jpeg);
PictureRes.ContentId = "logo_sml.jpg";
altView.LinkedResources.Add(PictureRes);
// Logo 2 //
string imageSource2 = (Server.MapPath("") + "\\booking_btn.jpg");
LinkedResource PictureRes2 = new LinkedResource(imageSource2, MediaTypeNames.Image.Jpeg);
PictureRes2.ContentId = "booking_btn.jpg";
altView.LinkedResources.Add(PictureRes2);
mail.AlternateViews.Add(altView);
// Send the email (using Web.Config file to store email Network link, etc.)
SmtpClient mySmtpClient = new SmtpClient();
mySmtpClient.Send(mail);
}
HTMLfile.htm
<html>
<body>
<img src="cid:logo_sml.jpg">
<br />
Hi %TEMPLATE_TOKEN1% .
<br />
<br/>
Your mobile no is %TEMPLATE_TOKEN2%
<br />
<br />
<img src="cid:booking_btn.jpg">
</body>
</html>
in your Web.Config file, inside your < configuration > block you need the following to allow testing in a TempMail folder on your c:\drive
<system.net>
<mailSettings>
<smtp deliveryMethod="SpecifiedPickupDirectory" from="madeupEmail#address.com">
<specifiedPickupDirectory pickupDirectoryLocation="C:\TempMail"/>
</smtp>
</mailSettings>
</system.net>
the only other things you will need at the top of your aspx.cs code behind file are the Using System includes (if I've missed one out you just right click on the unknown class and choose the 'Resolve' option)
using System.Net.Mail;
using System.Text;
using System.Reflection;
using System.Net.Mime; // need for mail message and text encoding
using System.IO;
Hope this helps someone and big thanks to the above poster for giving the answer needed to get the job done (as well as the other link in my code).
It works but im open to improvements.
cheers.
Thanks to the other answers I managed to get this to work - the only difference is the directory of the image - if the image is the same directory as the application than this can be used Ex:Directory.GetCurrentDirectory() + #"\ClientApp\public\img\blur.jpg
public void SendMail(string receiver, string subject, string content)
{
SmtpClient client = new SmtpClient(emailServiceConfig.SmtpServer);
client.EnableSsl = true; // Important ###
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(emailServiceConfig.Username, emailServiceConfig.Password);
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(emailServiceConfig.From);
mailMessage.To.Add(receiver);
//mailMessage.Body = content;
mailMessage.Subject = subject;
//Adding image =============================================
string html = #$"<html><body><img src=""cid:PageScreenshot"">{content}</body></html>";
AlternateView altView = AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html);
LinkedResource screenshotRes = new LinkedResource(Directory.GetCurrentDirectory() + #"\ClientApp\public\img\screeenshot2.jpg", MediaTypeNames.Image.Jpeg);
screenshotRes.ContentId = "PageScreenshot";
altView.LinkedResources.Add(screenshotRes);
mailMessage.AlternateViews.Add(altView);
client.Send(mailMessage);
}

Categories

Resources