Skip to content

Instantly share code, notes, and snippets.

@dbykadorov
Created February 17, 2014 09:26
Show Gist options
  • Save dbykadorov/9047455 to your computer and use it in GitHub Desktop.
Save dbykadorov/9047455 to your computer and use it in GitHub Desktop.
C#: workarround to avoid incorrect subject base64 encoding (with non-ascii subjects) // using .nem mvc 5 and mvc mail and Mandrill app
using System;
using System.Net;
using System.Net.Mail;
using System.Web.Mvc;
using Mvc.Mailer;
namespace MandrilloTest.Controllers
{
public class HomeController : Controller
{
/// other actions
public ActionResult MandrilloTest()
{
// Wrapper
string host = "smtp.mandrillapp.com";
string username = "YOUR_USERNAME";
string password = "YOUR_PASSWORD";
string port = "587";
// Test subjects
string[] subjects = new string[]
{
"примерпример пример", "примерпримерпример", "привет привет привет"
};
// Sent test messages
foreach (string subj in subjects)
{
// Send
var wrapper = new SmtpClientWrapper(getSmtpClient(host, port, username, password));
var testMailer = new Mailers.TestMailer();
testMailer.TestEncoding(subj).Send(wrapper);
}
return View();
}
/// Create new SmtpClient
private SmtpClient getSmtpClient(string host, string port, string username, string password)
{
var smtpClient = new SmtpClient(host, Convert.ToInt32(port));
if (string.Empty != username)
{
var smtpCredentials = new NetworkCredential(username, password);
smtpClient.Credentials = smtpCredentials;
}
return smtpClient;
}
}
}
/// Proofs
/// - Forum: http://social.msdn.microsoft.com/Forums/vstudio/en-US/4d1c1752-70ba-420a-9510-8fb4aa6da046/subject-encoding-on-smtpclientmailmessage
/// - Bug: https://connect.microsoft.com/VisualStudio/feedback/details/785710/mailmessage-subject-incorrectly-encoded-in-utf-8-base64
/// You can use this code or scaffold own mailer
using System.Text;
using Mvc.Mailer;
namespace MandrilloTest.Mailers
{
public interface ITestMailer
{
MvcMailMessage TestEncoding();
MvcMailMessage TestEncoding(string subject);
}
public class TestMailer : MailerBase, ITestMailer
{
public TestMailer()
{
MasterName="~/Views/TestMailer/_Layout.cshtml";
}
public MvcMailMessage TestEncoding()
{
return TestEncoding("TempSubject");
}
public virtual MvcMailMessage TestEncoding(string subject)
{
return Populate(x =>
{
x.Subject = subject;
x.ViewName = "TestEncoding";
x.To.Add("test@gmail.com");
x.BodyEncoding = Encoding.UTF8;
x.SubjectEncoding = Encoding.Unicode; // !!! Do the trick: spoof the MailMessage (base of the MvcMailMessage) to use quoted-prinable subject encoding
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment