Amazon SES not allowing diacritics characters in from field - c#

Using following SendEmailRequest containing characters with diacritics..
var sendRequest = new SendEmailRequest
{
Source = "Kůň <kun#test.com>",
Destination = destination,
Message = new Message
{
Subject = new Content(message.Subject),
Body = mailBody
}
};
..and dispatching it via Amazon SES results in sender being displayed incorrectly as KoH instead of Kůň in email client.
Is there a quick fix to get around this? How do I tell SES client to treat source as UTF-8? There is no such issue with subject.

The source code encoding must be declared.
Follow the link for more details about unicode:
https://msdn.microsoft.com/en-us/library/windows/desktop/dd374081%28v=vs.85%29.aspx

Related

Domain Label contains illegal character ':'

I am using Sharp.XMPP library for FCM. I can connect fine and it receives Upstream messages without issues. However, sending ack back to server has a response of Error Code 400 with following details
<JIDMalformed xmlns="urn:ietf:params:xml:ns:xmpp-stanzas" />
<text>"Malformed JID 'XXXXXX:XXXXXXXXXXXXX-XXXXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXX_XXXXX_XXXXX-XXXXXXXXXXXXXXXXXXX': domain label contains illegal character ':'"</text>
whereas the Xs replace the device registration token from which the Upstream message was received.
The code I'm using to form a message and send:
Sharp.Xmpp.Im.Message x = new Sharp.Xmpp.Im.Message(vFrom);
x.Data.SetAttribute("message_id", vMessageID);
x.Data.SetAttribute("message_type", "ack");
cl.SendMessage(x);
The string vFrom contains the device_token. I can not replace : as it is an essential part of device token and \: does not escape it either. What is the correct way of using colon in XML formats?
The issue here is that you've added Attributes to <data> tag whereupon they should be Elements to <gcm>
var msg = Xml.Element("message");
var elem = Xml.Element("gcm" ,"google:mobile:data"); //the gcm tag with xmlns attribute
Xml.Child(msg, elem); //assign child to message tag
var data = new {to = vFrom; message_id = vMessageID, message_type = "ack"};
JavaScriptSerializer serializer = new JavaScriptSerializer();
elem.Text(serializer.Serialize(data)); //not adding attributes
cl.SendMessage(new Sharp.Xmpp.Im.Message(new Sharp.Xmpp.Core.Message(data: elem)));
This here is an improved version of Sharp.XMPP for FCM. It includes the class Sharp.Xmpp.Core.Message that is probably not committed to github. This might help clarify.

What ItemPropertyPath is needed to get the sender of an mail via EWS?

We want to get the sender of an mail address via C# and EWS. We use Independentsoft´s Exchange Web Service for this task. It works fine by the following code:
var lItem = m_Service.GetMessage(ItemId);
return lItem.Sender.Name;
The Problem: When requesting the sender of thousands of messages, this could last a long time. It is much faster when we only request the necessary item properties:
var lItemPropertyPaths = new List<PropertyPath>() { ItemPropertyPath.? }; // -> replace the '?' by any property
var lItem = m_Service.GetMessage(ItemId, lItemPropertyPaths );
return lItem.Sender.Name;
The question is: What do we have to insert for the '?' in ItemPropertyPath.? to get the sender?

Lotus Note PassThruHTML

I’m trying to send an email using LOTUS NOTES with the help of “domino” dll (Programming language : C#).
I want to attach a mail signature into the body of email. I’m hoping to add a .jpg for the signature. I also have other email body formatting. Hence I have decided to use HTML for styling and attaching the signature. After browsing the web found out that in NotesRichTextStyle there is a property PassThruHTML. The legal values that can be given for it as per this link are (-1), (0), (255).
The ISSUE is that when I set (-1) the app popup a message saying that “Style value must be True, False, or STYLE_NO_CHANGE (YES, NO, or MAYBE for Java)”.
But in c sharp code it accepts only int values but not the values given in the popup.
Following is the C# code for the answer given by Ken Pespisa's reference link.
NotesSession LNSession = new NotesSession();
NotesDatabase LNDatabase = null;
NotesDocument LNDocument;
NotesMIMEEntity LNBody;
NotesStream LNStream;
NotesMIMEHeader LNHeader;
try
{
LNSession.Initialize(txtPassword.Text);
LNDatabase = LNSession.GetDatabase(txtServer.Text, txtUserName.Text, false);
LNStream = LNSession.CreateStream();
LNSession.ConvertMime = false;
//Create an email
LNDocument = LNDatabase.CreateDocument();
LNDocument.ReplaceItemValue("Form", "Memo");
LNBody = LNDocument.CreateMIMEEntity();
LNHeader = LNBody.CreateHeader("Subject");
LNHeader.SetHeaderVal("Add your subject here");
LNHeader = LNBody.CreateHeader("To");
LNHeader.SetHeaderVal("Give your recipient email address");
LNStream.WriteText("<html>");
LNStream.WriteText("<body bgcolor=\"blue\" text=\"white\">");
LNStream.WriteText("<table border=\"2\">");
LNStream.WriteText("<tr>");
LNStream.WriteText("<td>Hello World!</td>");
LNStream.WriteText("</tr>");
LNStream.WriteText("</table>");
LNStream.WriteText("</body>");
LNStream.WriteText("</html>");
LNBody.SetContentFromText(LNStream, "text/HTML;charset=UTF-8", MIME_ENCODING.ENC_IDENTITY_7BIT);
LNDocument.Send(false);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
If you're just sending email you should look at the NotesMimeEntity classes, and review this website for examples: http://www-01.ibm.com/support/docview.wss?uid=swg21098323
PassThruHTML won't help you much unless you're trying to display custom HTML in a browser when viewing a Notes document or form via Domino.

How to add html formatting to an email in C#? [duplicate]

Is there a better way to generate HTML email in C# (for sending via System.Net.Mail), than using a Stringbuilder to do the following:
string userName = "John Doe";
StringBuilder mailBody = new StringBuilder();
mailBody.AppendFormat("<h1>Heading Here</h1>");
mailBody.AppendFormat("Dear {0}," userName);
mailBody.AppendFormat("<br />");
mailBody.AppendFormat("<p>First part of the email body goes here</p>");
and so on, and so forth?
You can use the MailDefinition class.
This is how you use it:
MailDefinition md = new MailDefinition();
md.From = "test#domain.example";
md.IsBodyHtml = true;
md.Subject = "Test of MailDefinition";
ListDictionary replacements = new ListDictionary();
replacements.Add("{name}", "Martin");
replacements.Add("{country}", "Denmark");
string body = "<div>Hello {name} You're from {country}.</div>";
MailMessage msg = md.CreateMailMessage("you#anywhere.example", replacements, body, new System.Web.UI.Control());
Also, I've written a blog post on how to generate HTML e-mail body in C# using templates using the MailDefinition class.
Use the System.Web.UI.HtmlTextWriter class.
StringWriter writer = new StringWriter();
HtmlTextWriter html = new HtmlTextWriter(writer);
html.RenderBeginTag(HtmlTextWriterTag.H1);
html.WriteEncodedText("Heading Here");
html.RenderEndTag();
html.WriteEncodedText(String.Format("Dear {0}", userName));
html.WriteBreak();
html.RenderBeginTag(HtmlTextWriterTag.P);
html.WriteEncodedText("First part of the email body goes here");
html.RenderEndTag();
html.Flush();
string htmlString = writer.ToString();
For extensive HTML that includes the creation of style attributes HtmlTextWriter is probably the best way to go. However it can be a bit clunky to use and some developers like the markup itself to be easily read but perversly HtmlTextWriter's choices with regard indentation is a bit wierd.
In this example you can also use XmlTextWriter quite effectively:-
writer = new StringWriter();
XmlTextWriter xml = new XmlTextWriter(writer);
xml.Formatting = Formatting.Indented;
xml.WriteElementString("h1", "Heading Here");
xml.WriteString(String.Format("Dear {0}", userName));
xml.WriteStartElement("br");
xml.WriteEndElement();
xml.WriteElementString("p", "First part of the email body goes here");
xml.Flush();
Updated Answer:
The documentation for SmtpClient, the class used in this answer, now reads, 'Obsolete("SmtpClient and its network of types are poorly designed, we strongly recommend you use https://github.com/jstedfast/MailKit and https://github.com/jstedfast/MimeKit instead")'.
Source: https://www.infoq.com/news/2017/04/MailKit-MimeKit-Official
Original Answer:
Using the MailDefinition class is the wrong approach. Yes, it's handy, but it's also primitive and depends on web UI controls--that doesn't make sense for something that is typically a server-side task.
The approach presented below is based on MSDN documentation and Qureshi's post on CodeProject.com.
NOTE: This example extracts the HTML file, images, and attachments from embedded resources, but using other alternatives to get streams for these elements are fine, e.g. hard-coded strings, local files, and so on.
Stream htmlStream = null;
Stream imageStream = null;
Stream fileStream = null;
try
{
    // Create the message.
    var from = new MailAddress(FROM_EMAIL, FROM_NAME);
    var to = new MailAddress(TO_EMAIL, TO_NAME);
    var msg = new MailMessage(from, to);
    msg.Subject = SUBJECT;
    msg.SubjectEncoding = Encoding.UTF8;
 
    // Get the HTML from an embedded resource.
    var assembly = Assembly.GetExecutingAssembly();
    htmlStream = assembly.GetManifestResourceStream(HTML_RESOURCE_PATH);
 
    // Perform replacements on the HTML file (if you're using it as a template).
    var reader = new StreamReader(htmlStream);
    var body = reader
        .ReadToEnd()
        .Replace("%TEMPLATE_TOKEN1%", TOKEN1_VALUE)
        .Replace("%TEMPLATE_TOKEN2%", TOKEN2_VALUE); // and so on...
 
    // Create an alternate view and add it to the email.
    var altView = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
    msg.AlternateViews.Add(altView);
 
    // Get the image from an embedded resource. The <img> tag in the HTML is:
    //     <img src="pid:IMAGE.PNG">
    imageStream = assembly.GetManifestResourceStream(IMAGE_RESOURCE_PATH);
    var linkedImage = new LinkedResource(imageStream, "image/png");
    linkedImage.ContentId = "IMAGE.PNG";
    altView.LinkedResources.Add(linkedImage);
 
    // Get the attachment from an embedded resource.
    fileStream = assembly.GetManifestResourceStream(FILE_RESOURCE_PATH);
    var file = new Attachment(fileStream, MediaTypeNames.Application.Pdf);
    file.Name = "FILE.PDF";
    msg.Attachments.Add(file);
 
    // Send the email
    var client = new SmtpClient(...);
    client.Credentials = new NetworkCredential(...);
    client.Send(msg);
}
finally
{
    if (fileStream != null) fileStream.Dispose();
    if (imageStream != null) imageStream.Dispose();
    if (htmlStream != null) htmlStream.Dispose();
}
I use dotLiquid for exactly this task.
It takes a template, and fills special identifiers with the content of an anonymous object.
//define template
String templateSource = "<h1>{{Heading}}</h1>Dear {{UserName}},<br/><p>First part of the email body goes here");
Template bodyTemplate = Template.Parse(templateSource); // Parses and compiles the template source
//Create DTO for the renderer
var bodyDto = new {
Heading = "Heading Here",
UserName = userName
};
String bodyText = bodyTemplate.Render(Hash.FromAnonymousObject(bodyDto));
It also works with collections, see some online examples.
I would recomend using templates of some sort. There are various different ways to approach this but essentially hold a template of the Email some where (on disk, in a database etc) and simply insert the key data (IE: Recipients name etc) into the template.
This is far more flexible because it means you can alter the template as required without having to alter your code. In my experience your likely to get requests for changes to the templates from end users. If you want to go the whole hog you could include a template editor.
As an alternative to MailDefinition, have a look at RazorEngine https://github.com/Antaris/RazorEngine.
This looks like a better solution.
Attributted to...
how to send email wth email template c#
E.g
using RazorEngine;
using RazorEngine.Templating;
using System;
namespace RazorEngineTest
{
class Program
{
static void Main(string[] args)
{
string template =
#"<h1>Heading Here</h1>
Dear #Model.UserName,
<br />
<p>First part of the email body goes here</p>";
const string templateKey = "tpl";
// Better to compile once
Engine.Razor.AddTemplate(templateKey, template);
Engine.Razor.Compile(templateKey);
// Run is quicker than compile and run
string output = Engine.Razor.Run(
templateKey,
model: new
{
UserName = "Fred"
});
Console.WriteLine(output);
}
}
}
Which outputs...
<h1>Heading Here</h1>
Dear Fred,
<br />
<p>First part of the email body goes here</p>
Heading Here Dear Fred, First part of the email
body goes here
Emitting handbuilt html like this is probably the best way so long as the markup isn't too complicated. The stringbuilder only starts to pay you back in terms of efficiency after about three concatenations, so for really simple stuff string + string will do.
Other than that you can start to use the html controls (System.Web.UI.HtmlControls) and render them, that way you can sometimes inherit them and make your own clasess for complex conditional layout.
If you don't want a dependency on the full .NET Framework, there's also a library that makes your code look like:
string userName = "John Doe";
var mailBody = new HTML {
new H(1) {
"Heading Here"
},
new P {
string.Format("Dear {0},", userName),
new Br()
},
new P {
"First part of the email body goes here"
}
};
string htmlString = mailBody.Render();
It's open source, you can download it from http://sourceforge.net/projects/htmlplusplus/
Disclaimer: I'm the author of this library, it was written to solve the same issue exactly - send an HTML email from an application.
You might want to have a look at some of the template frameworks that are available at the moment. Some of them are spin offs as a result of MVC but that isn't required. Spark is a good one.
A commercial version which I use in production and allows for easy maintenance is LimiLabs Template Engine, been using it for 3+ years and allows me to make changes to the text template without having to update code (disclaimers, links etc..) - it could be as simple as
Contact templateData = ...;
string html = Template
.FromFile("template.txt")
.DataFrom(templateData )
.Render();
Worth taking a look at, like I did; after attempting various answers mentioned here.

Generating HTML email body in C#

Is there a better way to generate HTML email in C# (for sending via System.Net.Mail), than using a Stringbuilder to do the following:
string userName = "John Doe";
StringBuilder mailBody = new StringBuilder();
mailBody.AppendFormat("<h1>Heading Here</h1>");
mailBody.AppendFormat("Dear {0}," userName);
mailBody.AppendFormat("<br />");
mailBody.AppendFormat("<p>First part of the email body goes here</p>");
and so on, and so forth?
You can use the MailDefinition class.
This is how you use it:
MailDefinition md = new MailDefinition();
md.From = "test#domain.example";
md.IsBodyHtml = true;
md.Subject = "Test of MailDefinition";
ListDictionary replacements = new ListDictionary();
replacements.Add("{name}", "Martin");
replacements.Add("{country}", "Denmark");
string body = "<div>Hello {name} You're from {country}.</div>";
MailMessage msg = md.CreateMailMessage("you#anywhere.example", replacements, body, new System.Web.UI.Control());
Also, I've written a blog post on how to generate HTML e-mail body in C# using templates using the MailDefinition class.
Use the System.Web.UI.HtmlTextWriter class.
StringWriter writer = new StringWriter();
HtmlTextWriter html = new HtmlTextWriter(writer);
html.RenderBeginTag(HtmlTextWriterTag.H1);
html.WriteEncodedText("Heading Here");
html.RenderEndTag();
html.WriteEncodedText(String.Format("Dear {0}", userName));
html.WriteBreak();
html.RenderBeginTag(HtmlTextWriterTag.P);
html.WriteEncodedText("First part of the email body goes here");
html.RenderEndTag();
html.Flush();
string htmlString = writer.ToString();
For extensive HTML that includes the creation of style attributes HtmlTextWriter is probably the best way to go. However it can be a bit clunky to use and some developers like the markup itself to be easily read but perversly HtmlTextWriter's choices with regard indentation is a bit wierd.
In this example you can also use XmlTextWriter quite effectively:-
writer = new StringWriter();
XmlTextWriter xml = new XmlTextWriter(writer);
xml.Formatting = Formatting.Indented;
xml.WriteElementString("h1", "Heading Here");
xml.WriteString(String.Format("Dear {0}", userName));
xml.WriteStartElement("br");
xml.WriteEndElement();
xml.WriteElementString("p", "First part of the email body goes here");
xml.Flush();
Updated Answer:
The documentation for SmtpClient, the class used in this answer, now reads, 'Obsolete("SmtpClient and its network of types are poorly designed, we strongly recommend you use https://github.com/jstedfast/MailKit and https://github.com/jstedfast/MimeKit instead")'.
Source: https://www.infoq.com/news/2017/04/MailKit-MimeKit-Official
Original Answer:
Using the MailDefinition class is the wrong approach. Yes, it's handy, but it's also primitive and depends on web UI controls--that doesn't make sense for something that is typically a server-side task.
The approach presented below is based on MSDN documentation and Qureshi's post on CodeProject.com.
NOTE: This example extracts the HTML file, images, and attachments from embedded resources, but using other alternatives to get streams for these elements are fine, e.g. hard-coded strings, local files, and so on.
Stream htmlStream = null;
Stream imageStream = null;
Stream fileStream = null;
try
{
    // Create the message.
    var from = new MailAddress(FROM_EMAIL, FROM_NAME);
    var to = new MailAddress(TO_EMAIL, TO_NAME);
    var msg = new MailMessage(from, to);
    msg.Subject = SUBJECT;
    msg.SubjectEncoding = Encoding.UTF8;
 
    // Get the HTML from an embedded resource.
    var assembly = Assembly.GetExecutingAssembly();
    htmlStream = assembly.GetManifestResourceStream(HTML_RESOURCE_PATH);
 
    // Perform replacements on the HTML file (if you're using it as a template).
    var reader = new StreamReader(htmlStream);
    var body = reader
        .ReadToEnd()
        .Replace("%TEMPLATE_TOKEN1%", TOKEN1_VALUE)
        .Replace("%TEMPLATE_TOKEN2%", TOKEN2_VALUE); // and so on...
 
    // Create an alternate view and add it to the email.
    var altView = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
    msg.AlternateViews.Add(altView);
 
    // Get the image from an embedded resource. The <img> tag in the HTML is:
    //     <img src="pid:IMAGE.PNG">
    imageStream = assembly.GetManifestResourceStream(IMAGE_RESOURCE_PATH);
    var linkedImage = new LinkedResource(imageStream, "image/png");
    linkedImage.ContentId = "IMAGE.PNG";
    altView.LinkedResources.Add(linkedImage);
 
    // Get the attachment from an embedded resource.
    fileStream = assembly.GetManifestResourceStream(FILE_RESOURCE_PATH);
    var file = new Attachment(fileStream, MediaTypeNames.Application.Pdf);
    file.Name = "FILE.PDF";
    msg.Attachments.Add(file);
 
    // Send the email
    var client = new SmtpClient(...);
    client.Credentials = new NetworkCredential(...);
    client.Send(msg);
}
finally
{
    if (fileStream != null) fileStream.Dispose();
    if (imageStream != null) imageStream.Dispose();
    if (htmlStream != null) htmlStream.Dispose();
}
I use dotLiquid for exactly this task.
It takes a template, and fills special identifiers with the content of an anonymous object.
//define template
String templateSource = "<h1>{{Heading}}</h1>Dear {{UserName}},<br/><p>First part of the email body goes here");
Template bodyTemplate = Template.Parse(templateSource); // Parses and compiles the template source
//Create DTO for the renderer
var bodyDto = new {
Heading = "Heading Here",
UserName = userName
};
String bodyText = bodyTemplate.Render(Hash.FromAnonymousObject(bodyDto));
It also works with collections, see some online examples.
I would recomend using templates of some sort. There are various different ways to approach this but essentially hold a template of the Email some where (on disk, in a database etc) and simply insert the key data (IE: Recipients name etc) into the template.
This is far more flexible because it means you can alter the template as required without having to alter your code. In my experience your likely to get requests for changes to the templates from end users. If you want to go the whole hog you could include a template editor.
As an alternative to MailDefinition, have a look at RazorEngine https://github.com/Antaris/RazorEngine.
This looks like a better solution.
Attributted to...
how to send email wth email template c#
E.g
using RazorEngine;
using RazorEngine.Templating;
using System;
namespace RazorEngineTest
{
class Program
{
static void Main(string[] args)
{
string template =
#"<h1>Heading Here</h1>
Dear #Model.UserName,
<br />
<p>First part of the email body goes here</p>";
const string templateKey = "tpl";
// Better to compile once
Engine.Razor.AddTemplate(templateKey, template);
Engine.Razor.Compile(templateKey);
// Run is quicker than compile and run
string output = Engine.Razor.Run(
templateKey,
model: new
{
UserName = "Fred"
});
Console.WriteLine(output);
}
}
}
Which outputs...
<h1>Heading Here</h1>
Dear Fred,
<br />
<p>First part of the email body goes here</p>
Heading Here Dear Fred, First part of the email
body goes here
Emitting handbuilt html like this is probably the best way so long as the markup isn't too complicated. The stringbuilder only starts to pay you back in terms of efficiency after about three concatenations, so for really simple stuff string + string will do.
Other than that you can start to use the html controls (System.Web.UI.HtmlControls) and render them, that way you can sometimes inherit them and make your own clasess for complex conditional layout.
If you don't want a dependency on the full .NET Framework, there's also a library that makes your code look like:
string userName = "John Doe";
var mailBody = new HTML {
new H(1) {
"Heading Here"
},
new P {
string.Format("Dear {0},", userName),
new Br()
},
new P {
"First part of the email body goes here"
}
};
string htmlString = mailBody.Render();
It's open source, you can download it from http://sourceforge.net/projects/htmlplusplus/
Disclaimer: I'm the author of this library, it was written to solve the same issue exactly - send an HTML email from an application.
You might want to have a look at some of the template frameworks that are available at the moment. Some of them are spin offs as a result of MVC but that isn't required. Spark is a good one.
A commercial version which I use in production and allows for easy maintenance is LimiLabs Template Engine, been using it for 3+ years and allows me to make changes to the text template without having to update code (disclaimers, links etc..) - it could be as simple as
Contact templateData = ...;
string html = Template
.FromFile("template.txt")
.DataFrom(templateData )
.Render();
Worth taking a look at, like I did; after attempting various answers mentioned here.

Categories