Second Life of a Hungarian SharePoint Geek

March 17, 2014

Sending mails from a test SharePoint system, 2nd Edition

Filed under: Mails, Reflection, SP 2010 — Tags: , , — Peter Holpar @ 22:56

Last year I published a post describing how to fake mail sending of your applications in test system, without physically delivering mails via SMTP to addressees. In that post I utilized a solution via the smtp deliveryMethod to store the outgoing mails into a specific pickupDirectoryLocation instead of sending them to an SMTP server.

That solution is useful in simple situation, but have 2 major and 2 minor issues you face to, especially in more advanced topologies:

  1. The users of your system might have no access to the file system of the server. Even if you shared the folder and gave read permission to the users, there may be firewalls or other network components that do not allow accessing the share, just because the ports necessary for file and printer sharing are not open (see SMB, ports 445 and 139). It’s typical in the case of an intranet (like a public facing WCM site) or extranet solution, but may happen is your test and production systems are separated into various physical networks. Even if you could technically open the ports, the security policy of the organization should not allow this configuration change.
  2. If you have multiple applications in your SharePoint web application, and a few of these ones should be able to send out mails while others should not, or you have various processes running in the context of the SharePoint Timer Service (owstimer.exe), like workflows or event receivers conflicting in this requirement, you can not solve the conflict via a simple setting in the configuration.
  3. If you click on the .eml file the first time, the value of the Date modified field is changed to the current time (I explain the reason of this behavior in another post later), so it is more convenient to use the Date created field, and order the files based on the value of this field (newest files on the top).
  4. Even if your users have access to the mails in the file system, it’s not very helpful to see a list of .eml files with GUIDs as file name to choose which file to open (see sample screenshot below).

MailDirectory

You can check the Subject of the mail by opening the .eml file using Outlook or even a simple text editor, or by checking the file properties (Details tab). Neither of these options is very comfortable.

MailProperties

Instead of the configuration-based solution we can use a code-based approach that fulfills even more sophisticated requirements. In this sample I assume the helper classes are part of the application assembly. If you would like to place them into a separate helper assembly, you should consider to alter the internal access modifiers to public.

First we define an interface IMailSender with a single method, Send that has a single parameter of type MailMessage.

  1. interface IMailSender
  2. {
  3.     void Send(MailMessage message);
  4. }

Then we implement this interface in two classes, SmtpMailSender and DummyMailSender. Both of this types have a single public constructor with a single SPSite parameter.

In the SmtpMailSender class we send the mail as usual, through the the SMTP server configured in the OutboundMailServiceInstance of the corresponding web application.

  1. internal class SmtpMailSender : IMailSender
  2. {
  3.     private SPSite _site;
  4.  
  5.     public SmtpMailSender(SPSite site)
  6.     {
  7.         _site = site;
  8.     }
  9.  
  10.     public void Send(MailMessage message)
  11.     {
  12.         Trace.TraceInformation("Mail sending started via SmtpMailSender");
  13.  
  14.         string smtpHost = _site.WebApplication.OutboundMailServiceInstance.Server.Address;
  15.         SmtpClient smtpClient = new SmtpClient
  16.         {
  17.             Host = smtpHost
  18.         };
  19.         smtpClient.Send(message);
  20.  
  21.         Trace.TraceInformation("Mail sent to '{0}' via '{1}'", message.To, smtpHost);
  22.     }
  23. }

In the DummyMailSender class we read the content of the mail as a byte array, and store it in a SharePoint list (name of the list is stored in the GlobalConst.DummyMailList) as an attachment of an item that has its title as the mail subject.

  1. internal class DummyMailSender : IMailSender
  2. {
  3.     private SPSite _site;
  4.  
  5.     public DummyMailSender(SPSite site)
  6.     {
  7.         _site = site;
  8.     }
  9.  
  10.     public void Send(MailMessage message)
  11.     {
  12.         Trace.TraceInformation("Mail sending started via DummyMailSender");
  13.  
  14.         Assembly assembly = typeof(SmtpClient).Assembly;
  15.         Type mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");
  16.  
  17.         // see http://stackoverflow.com/questions/9595440/getting-system-net-mail-mailmessage-as-a-memorystream-in-net-4-5-beta
  18.         byte[] messageData = null;
  19.         using (MemoryStream mailStream = new MemoryStream())
  20.         {
  21.             ConstructorInfo mailWriterContructor = mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null);
  22.             object mailWriter = mailWriterContructor.Invoke(new object[] { mailStream });
  23.             MethodInfo sendMethod = typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic);
  24.             sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true }, null);
  25.  
  26.             messageData = mailStream.ToArray();
  27.         }
  28.  
  29.         SPList mailList = _site.RootWeb.Lists[GlobalConst.DummyMailList];
  30.         SPListItem mailItem = mailList.AddItem();
  31.         mailItem[SPBuiltInFieldId.Title] = message.Subject;
  32.         mailItem.Attachments.Add("Mail.eml", messageData);
  33.         mailItem.Update();
  34.  
  35.         string mailUrl = string.Format("{0}{1}?ID={2}", _site.Url, mailList.DefaultDisplayFormUrl, mailItem.ID);
  36.         Trace.TraceInformation("Dummy mail \"sent\" to '{0}', saved to '{1}'", message.To, mailUrl);
  37.     }
  38. }

Furthermore, we have a factory class that returns the right implementation of the IMailSender based on a condition evaluated in an extension method called IsTestSystem.

  1. internal static class MailSenderFactory
  2. {
  3.     public static IMailSender GetMailSender(SPSite site)
  4.     {
  5.         IMailSender mailSender = site.IsTestSystem() ? (IMailSender)new DummyMailSender(site) : (IMailSender)new SmtpMailSender(site);
  6.  
  7.         return mailSender;
  8.     }
  9. }

In our case we check if the site URL contains the substring “test”, of course you can use more advanced conditions and configuration options as well, like values stored in the site property bag, etc.

  1. public static bool IsTestSite(this SPSite site)
  2. {
  3.     string siteUrl = (site != null) ? site.Url.ToLower() : string.Empty;
  4.     bool result = siteUrl.Contains("test");
  5.  
  6.     return result;
  7. }

In the code of your application you can utilize these classes like illustrated below:

  1. // prepare mail
  2. MailMessage mail = new MailMessage("sender@company.com", "addressee@company.com");
  3. mail.Subject = "Test message";
  4. mail.Body = "This is the body of a test message";
  5. //Send mail
  6. IMailSender mailSender = MailSenderFactory.GetMailSender(site);
  7. mailSender.Send(mail);

In the test system you have to create manually the list for the mails in the root web. I find it useful, to add the Creation date field to the default view, and order the items based on that field (latest on the top. If you have multiple applications to test, you can use various lists for each one, so it is possible to give permissions only to the users who test the specific application.

You can enable opening .eml files in the browser itself via a PowerShell script like below:

$mimetype = "message/rfc822"
$webapp = Get-SPWebApplication http://yourwebappurl
$webapp.AllowedInlineDownloadedMimeTypes.Add($mimetype)
$webapp.Update()

However, only the body of the message will be displayed in the browser. So if the users need to see other information (like sender, addressee, subject, etc.), they should download the attachment and open it using Outlook.

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: