How to send email in richtext format to Outlook? - c#

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

Related

C# having trouble in sending email with both **Plain-text** & **Html** content

I am having trouble in sending email with both Plain-text & Html content.
In Outlook 2007 the plain-text message is never displayed.
And in Gmail email client by default plain-text is displaying. I need the HTML message to be displayed as default in both Outlook & Gmail, but user can change to plain-text if such settings are made on that system.
I am using following C# code to send emails:
private void SendEmail(string server, string from, string userName, string password, int port , string recipients)
{
MailMessage message = new MailMessage(from,recipients);
message.Subject = "This email message has multiple views.";
message.From = new MailAddress(from);
message.To.Add(recipients);
message.IsBodyHtml = false;
message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString("<html><head></head><body><h1>This is some HTML text2</h1></body></html>", null, MediaTypeNames.Text.Html));
message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString("This is some plain text2", null, MediaTypeNames.Text.Plain));
SmtpClient client = new SmtpClient(server);
client.Port = port;
NetworkCredential SMTPUserInfo = new NetworkCredential(userName, password);
client.UseDefaultCredentials = false;
client.Credentials = SMTPUserInfo;
client.Send(message);
}
The problem with this code is that (I am not sure), that in Outlook 2007 the email content is displayed initially like below image (default rendering HTML body as plain text):
When I right click & choose "Display as HTML", then the email content is displays like following image (rendering HTML body):
And when I use gmail.com to see the email then email content is displayed like following image (default rendering plain text):
EDIT 1: As suggested I have made changes to my code, now I can see the HTML Email content in Gmail. But in Outlook 2007 after setting plain-text as default view I see the HTML tags as string and it does not show Plain Text which i have drafted which is slightly different from html. Also how do i test the plain text email in Gmail as now in gmail i am receiving only HTML View and i didnt find any way to see plain text view though i have clicked on view original and changed view=om to view=dom in the URL as i have read it on google somewhere.
private void SendEmail(string server, string from, string userName, string password, int port , string recipients)
{
MailMessage message = new MailMessage(from,recipients);
message.Subject = "This email message has multiple views.";
message.From = new MailAddress(from);
message.To.Add(recipients);
message.Body = "This is some plain text2";
message.IsBodyHtml = true;
message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString("<html><head></head><body><h1>This is some HTML text2</h1></body></html>", null, MediaTypeNames.Text.Html));
//message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString("This is some plain text2", null, MediaTypeNames.Text.Plain));
SmtpClient client = new SmtpClient(server);
client.Port = port;
NetworkCredential SMTPUserInfo = new NetworkCredential(userName, password);
client.UseDefaultCredentials = false;
client.Credentials = SMTPUserInfo;
client.Send(message);
}
I would try adding the html view after the plain text view.
Also, I usually set the IsBodyHtml flag to true, even when I've got both views defined.
You should set MailMessage.Body to the clear text. Then add the html text as you do via AlternateViews.
At least this is how I have always sent emails with both text and html.
The email client should automatically choose html if it's capable of showing that. It shouldn't display the 'Alternate view' as it does now.
Edit:
I would not set 'IsBodyHtml' to true, it might confuse the mail program, since it's plain text.
Also I would set Encoding to Encoding.UTF8, but I doubt that would solve this problem.
Edit2:
Just checked my mail sender code. I always set a 'message id' header, don't know if that matters:
mailMessage.Headers.Add("message-id", "<" + DateTime.Now.Ticks + "#example.com>");

c# Send Email using Process.Start

I want to send simple email with no attachment using default email application.
I know it can be done using Process.Start, but I cannot get it to work. Here is what I have so far:
string mailto = string.Format("mailto:{0}?Subject={1}&Body={2}", "to#user.com", "Subject of message", "This is a body of a message");
System.Diagnostics.Process.Start(mailto);
But it simply opens Outlook message with pre-written text. I want to directly send this without having user to manually click "Send" button. What am I missing?
Thank you
You need to do this :
string mailto = string.Format("mailto:{0}?Subject={1}&Body={2}", "to#user.com", "Subject of message", "This is a body of a message");
mailto = Uri.EscapeUriString(mailto);
System.Diagnostics.Process.Start(mailto);
I'm not sure about Process.Start() this will probably always only open a mail message in the default Mail-App and not send it automatically.
But there may be two alternatives:
Send directly via SmtpClient Class
using Outlook.Interop
You need to do this:
SmtpClient m_objSmtpServer = new SmtpClient();
MailMessage objMail = new MailMessage();
m_objSmtpServer.Host = "YOURHOSTNAME";
m_objSmtpServer.Port = YOUR PORT NOS;
objMail.From = new MailAddress(fromaddress);
objMail.To.Add("TOADDRESS");
objMail.Subject = subject;
objMail.Body = description;
m_objSmtpServer.Send(objMail);

Secure Email in C#

I have a code for sending email through code, its as follows:
string subject = "SecureEmail: URS Scheduler - ";
string body = #"Message: My Message";
try
{
SmtpClient sm = new SmtpClient();
MailMessage msg = new MailMessage();
//msg.SubjectEncoding.
sm.Host = "email.myhost.com";
//Add Sender
msg.From = new MailAddress("abc#myhost.com");
//Add reciepents
sendMailToUsers(msg, "pqr#myhost.com");
//send message
msg.IsBodyHtml = true;
msg.Subject = subject;
msg.Body = body;
sm.Send(msg);
I am able to send message but its not encrypted, its a plain Text.
When I go to my Outlook mail client and Send Mail with above recipients and body, and subject starting with "SecureEmail:", I get an Encrypted Email with a button "Open Message". When I click on Open Message it redirects me to https://web1.zixmail.net/s/e?b=domain&m=encrypted msg and other info,then I login into it and and able to see the plain text of mail body.
Please help me in getting above behaviour through my code.
Your company is using ZixMail, and your Outlook has a plugin to enable this. If you want to send ZixMail from C#, you'll need to use their toolset and API. Reffer to ZixMail documentation and support.

Ques regarding sending email to a specific user

So I just googled n found out this code:-
MailMessage message = new MailMessage ("abc#somedomain.com","administrator#anotherdomain.com","Testing","This is a test mail");
Now my ques:-
How do I send a nicely formatted Email with links and all instead of simple text "This is a test mail" ??
I don't wanna attach no file
You could send the message body as HTML which will allow you to have links and such:
var message = new MailMessage("abc#somedomain.com", "administrator#anotherdomain.com");
message.Subject = "Testing";
message.IsBodyHtml = true;
message.Body = "<html><body><div>Test message</div>some link</body></html>";

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

Categories

Resources