sending mail along with embedded image using asp.net - c#

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

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.

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

send email as template in asp.net

i am able to send and receive emails through my application, but its jus plain text content. I want to send full formatted content decorated with css and div or tables.
How to do it?
I am using asp.net 3.5 VS2010.
public void Send(string To, string Subject, string Body)
{
System.Net.Mail.MailMessage m = new System.Net.Mail.MailMessage("mymail#gmail.com", To);
m.Subject = Subject;
m.Body = Body;
m.IsBodyHtml = true;
m.From = new MailAddress("mymail#gmail.com");
m.To.Add(new MailAddress(To));
SmtpClient smtp = new SmtpClient();
smtp.Host = "198.208.0.***";
NetworkCredential authinfo = new NetworkCredential("mymail#gmail.com", "password");
smtp.UseDefaultCredentials = false;
smtp.Credentials = authinfo;
smtp.Send(m);
}
calling this function like
Send("mynewmail#gmail.com", "testmail", "new test body");
this is my function.
The answer is here : http://social.msdn.microsoft.com/Forums/en/netfxnetcom/thread/c65502fa-955e-4fa1-b409-238bbb677df7
I think the main thing you're missing is the MIME Content Type on the LinkedResource.
myMagic.css:
body {
background-color: rgb(240,240,240);
font-family: Verdana,Arial,Helvetica,Sans-serif;
font-size: 10pt;
}
h2 {
background-color: rgb(255,255,128);
color: rgb(255,0,0);
}
p {
background-color: rgb(0,0,255);
color: rgb(0,255,0);
font-style: italic;
}
Program.cs:
using System.Net.Mail;
using System.Net.Mime;
namespace MailMessageHTML
{
class Program
{
private static MailMessage ConstructMessage(string from, string to, string subject)
{
const string textPlainContent =#"You need a HTML-capable mail agent to read this message.";
const string textHtmlContent =#"<html><head><link rel='stylesheet' type='text/css' href='cid:myMagicStyle' />
</head>
<body>
<h2>Hello world!</h2>
<p>This is a test HTML e-mail message.</p>
</body>
</html>
";
MailMessage result = new MailMessage(from, to, subject, textPlainContent);
LinkedResource cssResource = new LinkedResource("myMagic.css", "text/css");
//NOTE: Message encoding adds the surrounding <> on this Id cssResource.ContentId =myMagicStyle";
cssResource.TransferEncoding = TransferEncoding.SevenBit;
AlternateView htmlBody = AlternateView.CreateAlternateViewFromString( textHtmlContent , new ContentType("text/html"));
htmlBody.TransferEncoding = TransferEncoding.SevenBit;
htmlBody.LinkedResources.Add(cssResource);
result.AlternateViews.Add(htmlBody);
return result;
}
static void Main(string[] args)
{
MailMessage foo = ConstructMessage(
"sender#foo.com"
,"recipient#bar.com"
, "Test HTML message with style."
);
SmtpClient sender = new SmtpClient();
sender.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
sender.PickupDirectoryLocation = #"...\MailMessageHTML\bin\Debug\";
sender.Send(foo);
}
}
}
NOTE 1: I've specified TransferEncoding.SevenBit on the message parts above. You wouldn't normally do this in a production environment - I've only done it here so you can read the resultant .eml file with Notepad to see what was generated.
NOTE 2: A lot of mail agents won't honour stylesheets linked in message parts. A more-reliable way might be to use inline styles (i.e.: inline ... blocks within the HTML message body).
Good luck,
This answer got from : http://social.msdn.microsoft.com/Forums/en/netfxnetcom/thread/c65502fa-955e-4fa1-b409-238bbb677df7
If you don't need dynamic content (if/else or foreach) or model binding. I think put your template into a text file and use string.Format() is sufficient.
Otherwise, you'll need a template engine. This question may be a good reference for you.
Have a look at MvcMailer on github
It uses a viewengine to render emails so you have all the benefits of viewmodels and templating.
Have a look at http://www.campaignmonitor.com/css/ which shows how to apply CSS to emails.
Also, use inline CSS.. And are you setting emailMessage.IsBodyHtml = true; ?

format email body - .net 4.0

I'm using the following to send email from a site done in .net 4, c#.
MailMessage nMail = new MailMessage();
nMail.To.Add("new.address#test.com");
nMail.From = new MailAddress("me#me.com");
Mail.Subject = (" ");
nMail.Body = (" ");
SmtpClient sc = new SmtpClient("our server");
sc.Credentials = new System.Net.NetworkCredential("login", "pwd");
sc.Send(nMail);
Works fine, only thing I don't know how to do is format the body of the message to have multiple lines and include fields from the page itself.
Any pointers?
This is one way to make a message body with multiple lines.
var bodyBuilder = new StringBuilder();
bodyBuilder.AppendLine("First line.");
bodyBuilder.AppendLine("Second line.");
nMail.Body = bodyBuilder.ToString();
It should be obvious how to pull in values from your form now, too (i.e., the full power of string formatting is at your disposal now).
Follow this article. this will guide you through the way on how to format the mail body.
You can send message as HTML. Use IsBodyHtml property
MailMessage nMail = new MailMessage();
nMail.To.Add("new.address#test.com");
nMail.From = new MailAddress("me#me.com");
Mail.Subject = (" ");
nMail.Body = ("Line<br/>New line");
nMail.IsBodyHtml = true;
SmtpClient sc = new SmtpClient("our server");
sc.Credentials = new System.Net.NetworkCredential("login", "pwd");
sc.Send(nMail);
carefully look at this example, it should help how to pull in values from your form too (not the best method used though).

Categories

Resources