Skip to content

Instantly share code, notes, and snippets.

@jkodroff
Created January 22, 2014 16:08
Show Gist options
  • Save jkodroff/8561491 to your computer and use it in GitHub Desktop.
Save jkodroff/8561491 to your computer and use it in GitHub Desktop.
NServiceBus endpoint that handles email
using System;
using System.Configuration;
using System.Net;
using System.Text;
using NServiceBus;
using Newtonsoft.Json;
using RestSharp;
public class SendEmailHandler : IHandleMessages<SendEmail>
{
private readonly IBus m_bus;
public SendEmailHandler(IBus bus)
{
m_bus = bus;
}
public void Handle(SendEmail message)
{
var request = new RestRequest();
request.AddParameter("domain", ConfigurationManager.AppSettings["Mailgun.Domain"], ParameterType.UrlSegment);
request.Resource = "{domain}/messages";
request.AddParameter("from", message.From.ToMailgunParameter());
message.To.ForEach(to => request.AddParameter("to", to.ToMailgunParameter()));
(message.Bcc ?? new MailAddress[0]).ForEach(to => request.AddParameter("bcc", to.ToMailgunParameter()));
request.AddParameter("subject", message.Subject);
request.AddParameter(message.BodyFormat == EmailFormat.Html ? "html" : "text", message.Body);
(message.Attachments ?? new Attachment[0]).ForEach(attachment => request.AddFile("attachment", attachment.Contents, attachment.FileName, attachment.MimeType));
// These allow out of office messages to get back to the sender instead of Mailgun
request.AddParameter("o:native", "True");
request.AddParameter("o:native-send", "True");
request.Method = Method.POST;
var client = new RestClient {
BaseUrl = "https://api.mailgun.net/v2",
Authenticator = new HttpBasicAuthenticator("api", ConfigurationManager.AppSettings["Mailgun.ApiKey"])
};
var response = client.Execute(request);
if (response.StatusCode != HttpStatusCode.OK)
ThrowException(response);
m_bus.Reply(new EmailSent());
}
private void ThrowException(IRestResponse response)
{
var sb = new StringBuilder("Did not receive the expected HTTP OK response from Mailgun.");
sb.AppendLine("Instead, received this response:");
sb.AppendLine(JsonConvert.SerializeObject(response, Formatting.Indented));
throw new Exception(sb.ToString());
}
}
public class SendEmail : IMessage
{
public MailAddress[] To { get; set; }
public MailAddress From { get; set; }
public MailAddress[] Bcc { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public EmailFormat BodyFormat { get; set; }
public Attachment[] Attachments { get; set; }
}
public class Attachment
{
public string FileName { get; set; }
public byte[] Contents { get; set; }
public string MimeType { get; set; }
}
public class MailAddress
{
public string Address { get; set; }
public string DisplayName { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment