send email as template in asp.net - c#

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

Related

How to design SMTP mail content in c#

Software that I'm developing right now sends e-mail to responsible when a problem occurs in a production line. However while doing this email,I prefer it with a design like a card not a normal string.
I have just a little knowledge HTML and tried it but result was terrible.
So is there any API for c# to make this?
Look at this sample. May be it can help you.
MailAddress addressFrom = new MailAddress("jack.du#e-iceblue.com", "Jack Du");
MailAddress addressTo = new MailAddress("susanwong32#outlook.com");
MailMessage message = new MailMessage(addressFrom, addressTo);
message.Date = DateTime.Now;
message.Subject = "Sending Email with HTML Body";
string htmlString = #"<html>
<body>
<p>Dear Ms. Susan,</p>
<p>Thank you for your letter of yesterday inviting me to come for
an interview on Friday afternoon, 5th July, at 2:30.I shall be happy to be there as
requested and will bring my diploma and other papers with me.</p>
<p>Sincerely,<br>-Jack</br></p>
</body>
</html>
";
message.BodyHtml = htmlString;
SmtpClient client= new SmtpClient();
client.Host = "smtp.outlook.com";
client.Port = 587;
client.Username = addressFrom.Address;
client.Password = "password";
client.ConnectionProtocols = ConnectionProtocols.Ssl;
client.SendOne(message);
Console.WriteLine("Sent Successfully!");
Console.Read();
You should use the below property in order to get your content in the Html format.
message.IsBodyHtml = true;
Hope this is helpful

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

How to send email in richtext format to Outlook?

It works great to send emails (to Outlook) in HTML format by assigning the text/html content type string like so:
using (MailMessage message = new MailMessage())
{
message.From = new MailAddress("--#---.com");
message.ReplyTo = new MailAddress("--#---.com");
message.To.Add(new MailAddress("---#---.com"));
message.Subject = "This subject";
message.Body = "This content is in plain text";
message.IsBodyHtml = false;
string bodyHtml = "<p>This is the HTML <strong>content</strong>.</p>";
using (AlternateView altView = AlternateView.CreateAlternateViewFromString(bodyHtml,
new ContentType(MediaTypeNames.Text.Html)))
{
message.AlternateViews.Add(altView);
SmtpClient smtp = new SmtpClient(smtpAddress);
smtp.Send(message);
}
}
The email is correctly recognized as HTML in Outlook (2003).
But if I try rich text:
MediaTypeNames.RichText;
Outlook doesn't detect this, it falls back to plain text.
How do I send email in rich text format?
The bottom line is, you can't do this easily using System.Net.Mail.
The rich text in Outlook is sent as a winmail.dat file in the SMTP world (outside of Exchange).
The winmail.dat file is a TNEF message. So, you would need to create your richtext inside of the winmail.dat file (formatted to TNEF rules).
However, that's not all. Outlook uses a special version of compressed RTF, so, you would also need to compress your RTF down, before it's added to the winmail.dat file.
The bottom line, is this is difficult to do, and unless the client really, really needs this functionality, I would rethink it.
This isn't something you can do with a few lines of code in .NET.
You can also achieve this by adding another alternate view before your calendar view as below:
var body = AlternateView.CreateAlternateViewFromString(bodyHtml, new System.Net.Mime.ContentType("text/html"));
mailMessage.AlternateViews.Add(body);
This worked for me..
public void sendUsersMail(string recipientMailId, string ccMailList, string body, string subject)
{
try
{
MailMessage Msg = new MailMessage();
Msg.From = new MailAddress("norepl#xyz.com", "Tracker Tool");
Msg.To.Add(recipientMailId);
if (ccMailList != "")
Msg.CC.Add(ccMailList);
Msg.Subject = subject;
var AltBody = AlternateView.CreateAlternateViewFromString(body, new System.Net.Mime.ContentType("text/html"));
Msg.AlternateViews.Add(AltBody);
Msg.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("mail.xyz.com");
smtp.Send(Msg);
smtp.Dispose();
}
catch (Exception ex)
{
}
}

send smtp mail including html to gmail account

I've found this small code that sends email to gmail users. I'd like the body of the mail to contain html (for example, decoding a link for it to hold different text than the url it's pointing to).
I am using c# .net 3.5. I've used these classes in my code:
MailMessage
SmtpClient
How can this be done?
Here's a copy of my code:
MailMessage message = new MailMessage("me#gmail.com", WebCommon.UserEmail, "Test", context.Server.HtmlEncode("<html> <body> <a href='www.cnn.com'> test </a> </body> </html> "));
System.Net.NetworkCredential cred = new System.Net.NetworkCredential("him#gmail.com", "myPwd");
message.IsBodyHtml = true;
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com");
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
smtp.Credentials = cred;
smtp.Port = 587;
smtp.Send(message);
Thanks!
Something like this should work:
Note that MailMessage refers to System.Net.MailMessage. There is also System.Web.MailMessage, which I have never used and -as far as I know- is obsolete.
MailMessage message = new MailMessage();
// Very basic html. HTML should always be valid, otherwise you go to spam
message.Body = "<html><body><p>test</p></body></html>";
// QuotedPrintable encoding is the default, but will often lead to trouble,
// so you should set something meaningful here. Could also be ASCII or some ISO
message.BodyEncoding = Encoding.UTF8;
message.IsBodyHtml = true;
// No Subject usually goes to spam, too
message.Subject = "Some Subject";
// Note that you can add multiple recipients, bcc, cc rec., etc. Using the
// address-only syntax, i.e. w/o a readable name saves you from some issues
message.To.Add("someone#gmail.com");
// SmtpHost, -Port, -User, -Password must be a valid account you can use to
// send messages. Note that it is very often required that the account you
// use also has the specified sender address associated!
// If you configure the Smtp yourself, you can change that of course
SmtpClient client = new SmtpClient(SmtpHost, SmtpPort) {
Credentials = new NetworkCredential(SmtpUser, SmtpPassword),
EnableSsl = enableSsl;
};
try {
// It might be necessary to enforce a specific sender address, see above
if (!string.IsNullOrEmpty(ForceSenderAddress)) {
message.From = new MailAddress(ForceSenderAddress);
}
client.Send(message);
}
catch (Exception ex) {
return false;
}
For more sophisticated templating solutions that render the Body html rather than hard-codin it, there is, for example, the EMailTemplateService in MvcContrib which you can use as a guideline.
One way to do it is to create an alternate html view of the email:
MailMessage message = new MailMessage();
message.Body = //plain-text version of message
//set up message...
//create html view
string htmlBody = "<html>...</html>";
htmlView = AlternateView.CreateAlternateViewFromString(htmlBody, null, "text/html");
message.AlternateViews.Add(htmlView);
//send message
smtpClient.Send(message);

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