Unable to decode danish characters for email - c#

I have some code to send an email. data for email is coming from third party API, which will look like this å equivalent of it is danish character å. but email shows s å .
Is there any way i can transform this one in to correct?
My code to send mail is like this
SmtpClient client = new SmtpClient();
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
foreach (string toEmail in toEmails.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
mail.To.Add(toEmail.Trim());
mail.Subject = subject;
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = body;
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = isHtml;
mail.Priority = MailPriority.Normal;
if (attachments != null)
{
foreach (string key in attachments.Keys)
{
Attachment mailAttachment = new Attachment(attachments[key], key);
mail.Attachments.Add(mailAttachment);
}
}
client.Send(mail);
retValue = true;
Note: Fixed the issue by using L.B's answer . but i am still having some issues like
this. in my email body

Use HttpUtility or WebUtility class
var str = HttpUtility.HtmlDecode("å");
var str = WebUtility.HtmlDecode("å");

Related

How Can I Add New Line In Email Body?

I am Sending Mail to Specific User, in mail.body after my message I wanted to Add Few more details which will be in new line, I tried br,n, Environment.NewLine but nothing seems to be working, is there a way which I can try.
Thank you In Advance.
protected void SendMail()
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("xyz");
mail.To.Add("abc");
mail.Subject = "INCOMPLETE APPLICATION CASE ID [CASE ID]";
mail.IsBodyHtml = true;
mail.Body = "Your Incomplete Grade Application has been Result[]";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(Server.MapPath("files/CS00022904.pdf"));
mail.Attachments.Add(attachment);
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "10.12.46.3";
smtp.Port = 25;
smtp.EnableSsl = false;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential("", "");
}
smtp.Send(mail);
}
You should be able to use br:
mail.Body = "Your Incomplete Grade Application has been Result[] <br /> Here is another line of text!";
There are few ways, one of these:
var sb = new StringBuilder();
sb.Append("Line 1").Append("<br />");
. . . . .
sb.Append("Line N").Append("<br />");
// Sometimes later
mail.Body = sb.ToString();
Advantage of string builder is that you can efficiently add lines in loop and in differed way. you can pass it to different methods and keep adding lines, and use it in the end. This is also helpful if your text stored as lines and you can iterated them.
Since the BodyFormat is set to HTML, you can just add <br /> to the body string.

SmtpClient sending raw Html

Could anyone tell me why the following code is sending out emails in raw Html? As in, the email looks like when you view a page source.
I have cut down the code so as not to include attachments and from addresses.
If I disable the line with the alternate view the email renders correctly but I also want to send out a plain text version.
using (SmtpClient client = GetSmtpClient(settings)) {
using (MailMessage message = new MailMessage()) {
message.IsBodyHtml = true;
message.BodyEncoding = System.Text.Encoding.GetEncoding("iso-8859-1");
message.To.Add(toList);
message.Subject = subject;
message.Body = htmlTemplate;
message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(textTemplate, new ContentType("text/plain")));
client.Send(message);
}
}
Edit: The message was originally sending text as the main body and html as the alternative view but I have run into a problem with accented and foreign characters as described here and wanted to set IsBodyHtml to true, which forces me to set html to the main view.
I had problems with this also but here's a very much cutdown version of code that worked for me...
private MailMessage CreateEmailMessage(string emailAddress) {
MailMessage msg = new MailMessage();
msg.From = new MailAddress(FromEmailAddress, FromName);
msg.To.Add(new MailAddress(emailAddress));
msg.Subject = "Msg Subject here";
string textBody = File.ReadAllText(TextTemplateFile);
string htmlBody = "";
if (EmailFormat == "html") {
htmlBody = File.ReadAllText(HtmlTemplateFile);
foreach (Attachment inline in InlineAttachments) {
inline.ContentDisposition.Inline = true;
msg.Attachments.Add(inline);
}
AlternateView alternateHtml = AlternateView.CreateAlternateViewFromString(htmlBody,
new ContentType("text/html"));
msg.AlternateViews.Add(alternateHtml);
AlternateView alternateText = AlternateView.CreateAlternateViewFromString(textBody,
new ContentType("text/plain"));
msg.AlternateViews.Add(alternateText);
}
else {
msg.Body = textBody;
}
return msg;
}
In the end I realised that the 'htmlTemplate' string being passed into the method was defining charset=ISO-8859-1 in the head of the email and therefore overriding any changes I was making in the code.
I changed the charset to UTF-8, and restored my code to this:
using (SmtpClient client = GetSmtpClient(settings)) {
using (MailMessage message = new MailMessage()) {
message.To.Add(toList);
message.Subject = subject;
message.Body = textTemplate;
message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(htmlTemplate, new ContentType("text/html")));
client.Send(message);
}
}
and can now send both text and html templates as well as cover the accented characters problem.

problem with send mail method

In this method i send mail
var mail = new MailMessage();
mail.Subject = subject;
mail.SubjectEncoding = Encoding.UTF8;
mail.IsBodyHtml = mailServer.EsHtml;
mail.From = new MailAddress(mailFrom, nomFrom,Encoding.UTF8);
foreach(var item in mailTo)
mail.To.Add(new MailAddress(item.Key, item.Value, Encoding.UTF8));
foreach(var item in mailCC)
mail.Bcc.Add(new MailAddress(item.Key, item.Value, Encoding.UTF8));
mail.Body = message;
mail.BodyEncoding = Encoding.Unicode;
mail.Attachments.Add(new Attachment(attachments));
var clientMail = new SmtpClient();
clientMail.Credentials = new System.Net.NetworkCredential(mailFrom, passMail);
if(mailServer.PuertoCorreo.HasValue)
clientMail.Port = mailServer.PuertoCorreo.Value;
clientMail.Host = mailServer.ServidorCorreo;
clientMail.EnableSsl = mailServer.HabilitarSSL;
clientMail.Send(mail);
And it works fine but in gmail in the body i got this text਍猀搀搀昀ഀ more text and hotmail in attach name i got this 牰敵慢瀮晤.What is wrong in the method?
Try this:
mail.BodyEncoding = System.Text.Encoding.UTF8;

Problem sending email with SmtpClient in C#

I have an ASP.Net/MVC application and I'm trying to send HTML emails. I'm doing this by reading in an HTML file with tokens, then replacing the tokens. That part is fine and generates HTML that is exactly what I want, but when I send the email, what I'm receiving looks like -
<style type=3D"text/css">=
=0D=0A.styleTitles=0D=0A{=0D=0Afont-weight:=bold;=0D=0A}=0D=0A
.style1=0D=0A {=0D=0A
and should look like
<style type="text/css">
.styleTitles
{
font-weight: bold;
}
.style1
{
height: 15px;
}
I've looked on the web and I can't seem to find the correct syntax to send the message. I've seen some solutions, but none seem to work.
My current test code is -
SmtpClient smtpclient = new SmtpClient();
MailMessage message = new MailMessage();
MailAddress SendFrom = new MailAddress("xxxx#abc.com");
MailAddress SendTo = new MailAddress("zzzz#gmail.com");
MailMessage MyMessage = new MailMessage(SendFrom, SendTo);
var plainView = AlternateView.CreateAlternateViewFromString(msgBody,null,"text/html");
plainView.TransferEncoding = System.Net.Mime.TransferEncoding.SevenBit;
MyMessage.AlternateViews.Add(plainView);
MyMessage.IsBodyHtml = true;
MyMessage.Subject = subjectLine;
MyMessage.Body = msgBody;
smtpclient.Send(MyMessage);
Any Suggestions?
Maybe something like this:
var plainView = AlternateView.CreateAlternateViewFromString(msgBody, new ContentType("text/plain; charset=UTF-8"));
MyMessage.AlternateViews.Add(plainView);
MyMessage.BodyEncoding = Encoding.UTF8;
MyMessage.IsBodyHtml = true;
MyMessage.Subject = subjectLine;
MyMessage.Body = msgBody;
Try this change:
plainView.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
To set the transfer encoding to 8bit, taken from here , you have to :
message.Body = null;
using (AlternateView body =
AlternateView.CreateAlternateViewFromString(
"Some Message Body",
message.BodyEncoding,
message.IsBodyHtml ? "text/html" : null))
{
body.TransferEncoding =
TransferEncoding.SevenBit;
message.AlternateViews.Add(body);
}
This might not be the answer you need, but have you considered using XSLT for the translation of your email messages? I'm busy with a project that sends emails, and its pretty nice to use XSLT as part of the solution. Also means in future the template can easily be customized in an industry standardized way, maybe you should consider making the change?
It's strange, but more simple code is work for me:
var message = new MailMessage(Email, mailTo);
message.IsBodyHtml = true;
message.SubjectEncoding = message.BodyEncoding = Encoding.UTF8;
message.Subject = "Subject";
message.Body = msgBody;
smtpclient.Send(message);
string emailMessage="a skjdhak kdkand";
MailMessage mail = new MailMessage();
mail.To.Add(obj_Artist.EmailAddress);
mail.From = new MailAddress(EmailList[0].FromEmail, "Sentric Music - Rights Management");
mail.Subject = (EmailList[0].Subject);
if (EmailList[0].BCC1 != null && EmailList[0].BCC1 != string.Empty)
{
mail.Bcc.Add(EmailList[0].BCC1);
}
if (EmailList[0].BCC2 != null && EmailList[0].BCC2 != string.Empty)
{
mail.Bcc.Add(EmailList[0].BCC2);
}
if (EmailList[0].CC1 != null && EmailList[0].CC1 != string.Empty)
{
mail.CC.Add(EmailList[0].CC1);
}
if (EmailList[0].CC2 != null && EmailList[0].CC2 != string.Empty)
{
mail.CC.Add(EmailList[0].CC2);`enter code here`
}
string Body = emailMessage;
mail.Body = Body;
mail.BodyEncoding = System.Text.Encoding.GetEncoding("utf-8");
mail.IsBodyHtml = true;
AlternateView plainView = AlternateView.CreateAlternateViewFromString
(System.Text.RegularExpressions.Regex.Replace(Body, #"<(.|\n)*?>", string.Empty), null, "text/plain");
System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(Body, null, "text/html");
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);
SmtpClient smtp = new SmtpClient();
smtp.EnableSsl = true;
smtp.Send(mail);

Send HTML email via C# with SmtpClient

How do I send an HTML email? I use the code in this answer to send emails with SmtpClient, but they're always plain text, so the link in the example message below is not formatted as such.
<p>Welcome to SiteName. To activate your account, visit this URL:
http://SiteName.com/a?key=1234.
</p>
How do I enable HTML in the e-mail messages I send?
This is what I do:
MailMessage mail = new MailMessage(from, to, subject, message);
mail.IsBodyHtml = true;
SmtpClient client = new SmtpClient("localhost");
client.Send(mail);
Note that I set the mail message html to true: mail.IsBodyHtml = true;
I believe it was something like:
mailObject.IsBodyHtml = true;
IsBodyHtml = true is undoubtedly the most important part.
But if you want to provide an email with both a text/plain part and a text/html part composed as alternates, it is also possible using the AlternateView class:
MailMessage msg = new MailMessage();
AlternateView plainView = AlternateView
.CreateAlternateViewFromString("Some plaintext", Encoding.UTF8, "text/plain");
// We have something to show in real old mail clients.
msg.AlternateViews.Add(plainView);
string htmlText = "The <b>fancy</b> part.";
AlternateView htmlView =
AlternateView.CreateAlternateViewFromString(htmlText, Encoding.UTF8, "text/html");
msg.AlternateViews.Add(htmlView); // And a html attachment to make sure.
msg.Body = htmlText; // But the basis is the html body
msg.IsBodyHtml = true; // But the basis is the html body
Apply the correct encoding of the Mailbody.
mail.IsBodyHtml = true;
i have an idea , you can add a check box to your project for sending email as html as an option for user , and add this code to enable it :
MailMessage mail = new MailMessage(from, to, subject, message);
if(checkBox1.CheckState == CheckState.Checked )
{
mail.IsBodyHtml = true;
}
SmtpClient client = new SmtpClient("localhost");
client.Send(mail);
If you are using Mailkit,We can use TextBody,HtmlBody and Both for message body. Just write this code. It will help you
MimeMessage mailMessage = new MimeMessage();
mailMessage.From.Add(new MailboxAddress(senderName, sender#address.com));
mailMessage.Sender = new MailboxAddress(senderName, sender#address.com);
mailMessage.To.Add(new MailboxAddress(emailid, emailid));
mailMessage.Subject = subject;
mailMessage.ReplyTo.Add(new MailboxAddress(replyToAddress));
mailMessage.Subject = subject;
var builder = new BodyBuilder();
builder.HtmlBody = "Hello There";
mailMessage.Body = builder.ToMessageBody();
try
{
using (var smtpClient = new SmtpClient())
{
smtpClient.Connect("HostName", "Port", MailKit.Security.SecureSocketOptions.None);
smtpClient.Authenticate("user#name.com", "password");
smtpClient.Send(mailMessage);
Console.WriteLine("Success");
}
}
catch (SmtpCommandException ex)
{
Console.WriteLine(ex.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

Categories