Sending a mail as both HTML and Plain Text in .net - c#

I'm sending mail from my C# Application, using the SmtpClient. Works great, but I have to decide if I want to send the mail as Plain Text or HTML. I wonder, is there a way to send both? I think that's called multipart.
I googled a bit, but most examples essentially did not use SmtpClient but composed the whole SMTP-Body themselves, which is a bit "scary", so I wonder if something is built in the .net Framework 3.0?
If not, is there any really well used/robust Third Party Library for sending e-Mails?

The MSDN Documentation seems to miss one thing though, I had to set the content type manually, but otherwise, it works like a charm :-)
MailMessage msg = new MailMessage(username, nu.email, subject, body);
msg.BodyEncoding = Encoding.UTF8;
msg.SubjectEncoding = Encoding.UTF8;
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlContent);
htmlView.ContentType = new System.Net.Mime.ContentType("text/html");
msg.AlternateViews.Add(htmlView);

What you want to do is use the AlternateViews property on the MailMessage
http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews.aspx

Just want to add that you can use defined constants MediaTypeNames.Text.Html and MediaTypeNames.Text.Plain instead of "text/html" and "text/plain", which is always a preferable way. It's in System.Net.Mime namespace.
So in the example above, it would be:
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlContent, null, MediaTypeNames.Text.Html);

I'm just going to put a note here for anyone that's having problems and finds their way to this page - sometimes, Outlook SMTP servers will reconvert outgoing email. If you're seeing your plain-text body vanish entirely, and nothing but base64-encoded attachments, it might be because your server is reencoding the email. Google's SMTP server does not reencode email - try sending through there and see what happens.

On top of using AlternateViews views to add both the html and the plain text view, make sure you are not also setting the body of the Mail Message object.
// do not do this:
var msg = new MailMessage(model.From, model.To);
msg.Body = compiledHtml;
As it will make your email contain the html content in both views, overriding the alternative views.

For the people(like me) who've had the problem of gmail displaying the plaintext part instead of the html part.
Gmail seems to always display the last part in your message.
So if you've added the html part before your plain text part chances are gmail will always show the plain text variant.
To fix this you can simply add the plain text part before your html part.

For anyone who bumped into this issue you might want to check if you have preheader tags in your html.
In my html I've added a tag with a phrase of "Activate your client admin account by clicking the link.".
It seems like gmail is flagging the phrase "clicking the link" after removing it, all my emails that has been sent, are going straight to the inbox.

Related

Inserting Image With Inline HTML

I am new to Web APIs, so sorry if I am missing information. I am trying to send an email from my web api with an image (not as an attachment), but I am having issues with the inline html.
Example (This is in the WebAPI Controller)
message Body = "<p>Here is an image</p>" + Model.Image;
Now this will not work, as it displays "System.Byte[]", so my alternative was to convert it with some inline html, such as...
message Body = "<p>Here is an image</p>" + "<img src=\"data:image/gif;base64,#System.Convert.ToBase64String{Model.Image)\" />;
This will return an empty element. What am I doing wrong? If I were to guess, I am not using quotations correctly, but I cannot find anyone trying to insert an image the way I am.
Site note - If I see what is being sent from the mobile app for the image, I am getting a huge string of text that is always the same, regardless of whether it is a different image. I thought I would use that like src="data:image/gif;base64,", but I just get a long string returned in the email.
You need to host your image somewhere else and use the full path. Example:
<img scr="https://static.makeuseof.com/wp-content/uploads/2017/12/test-html-online-670x335.jpg" />
Most email clients do not display base64 images. My solution was to attach the image to the email by using the following code.
MemoryStream ms = new MemoryStream(Model.Image);
message.Attachments.Add(new Attachment(ms, "Image.png", "image/png"));
I did not need to convert from byte to base64, as this was done on the mobile app before being sent to the API, so I just referenced the value that was stored in the model.

Sending multipart email in ASP.NET with System.Net.Mail - received email has no body

I'm very confused about a problem with sending multipart emails in ASP.NET. I'm using code which I'm sure has worked before, but the received email appears to have no body.
The key bit of code is this:
message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(plainBody, null, MediaTypeNames.Text.Plain));
message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html));
I can verify that plainBody is valid text and htmlBody is valid HTML. Apart from this I'm creating a very simple MailMessage with subject, from and to. I'm not setting any other properties of MailMessage and I'm sending with the standard System.Net.Mail.SmtpClient using Google credentials I've used many times before.
When the email arrives it appears to be completely empty.
If I replace the above two lines with the following (no other changes) then the HTML email arrives correctly.
message.Body = htmlBody;
message.IsBodyHtml = true;
So what could be the cause of my empty emails? I've tried simplifying the HTML right down to a single word wrapped in <b> tags so it's not related to the body content and, as I say, I've used similar code many times before with no problems. I've tested receipt of the emails in GMail and Office 365, both with same result.
Suggestions very welcome.
Why don't you break that piece of the code into two objects.
AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
message.AlternateViews.Add(alternate);
Put a break point in the second line and see whats in the alternate object. Maybe that might give you a little more insight into what's going on in your code.
You cannot set the mail with two different bodies. Since one of the parts is HTML, you need to treat all mail as HTML, just appending the plaintext normally - since the plaintext has no HTML encode inside, the text will appear as plaintext.

EWS reply mail with original body

When i want to reply a mail via EWS like below, if I retrieve a email body in html format like below. How can I put some reply text conveniently, just at the top of the original message?
Although I can parse the html, I am wondering there is any smart way doing it. thank you
EmailMessage mesg = email.CreateReply(false).Save();
mesg.Load();
MessageBody lvMessageBody = mesg.Body;
You should be able to do this by setting the BodyPrefix property on the reply. See https://msdn.microsoft.com/EN-US/library/office/dn617213(v=exchg.150).aspx

German characters sending data using POST method from ASP page to PHP page

I have a problem with sending data from ASP with the POST Method to a PHP page.
I would like to send mail with names. And since I live in Austria the names are in German and we have some Special characters. These characters don't arrive write.
I'm still pretty new to programming with C# btw. I had the Website before in Java-Script but I had to connect it with a database and therefore I switched to C# and now I'm like a "babe in the woods".
this.hdnDaten.Value = "ÄÖÜ|äöü|ß|é|#";
// mit POST versuchen
using (var client = new WebClient())
{
var postData = new System.Collections.Specialized.NameValueCollection();
postData.Add("von", this.hdnVon.Value);
postData.Add("an", this.hdnAn.Value);
postData.Add("betreff", this.hdnBetreff.Value);
postData.Add("daten", this.hdnDaten.Value);
byte[] response = client.UploadValues("http://xxxxxx.php", "POST", postData);
var responsebody = Encoding.UTF8.GetString(response);
}
And this is how the characters (in this.hdnDaten.Value) from above arrive in the mail-body:
ÄÖÜ|äöü|ß|é|#
Does anybody know what I can do to get the same characters in the end?
Edit 20143013: I think I have a clue: I have to encode the postData into ANSI (Codepage 1252). I tried do do this, but it doesn't work. Does anybody have an Idea how I could do this?
Edit 20140320: I don't even dare to give you the answer: I was looking all the time in the wrong place (somewhat like MH370): The problem was with the receiving side of the mail (I was using a POP3-Viewer for testing); when I downloaded the mail to Outlook everything was OK. The funny thing was that this didn't happen in the original (Javascript) Version that's why I was looking at the wrong place.
Thanks
Eddie
Try setting client.Encoding to UTF-8 before calling UploadValues. Also ensure that you read the text as UTF-8 on the server.
Try this.hdnDaten.Value = HttpUtility.UrlEncode("ÄÖÜ|äöü|ß|é|#"); on your post parameters.
on PHP you'll need to decode the parameters via html_entity_decode

Email formating using System.Net.Mail smtpclient

How do I format the body of the email so it doesn't look so old school :)
I've tried sending html through it, but it just comes out as html in the body of the email.
Thanks for any help and assistance, cheers!
Set the IsBodyHtml property to true.
Including the above, I use StringBuilder's to format the contents of my emails like so:
StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0} submitted the following information from the site:", txtName.Text);
I just find it's helpful in visualizing the outcome rather than doing +='s and such.

Categories