Recently I work quite a lot with the SharePoint calendar and the incoming mail feature of SharePoint. During my experiments I found an interesting problem, namely how one can check from code if a specific e-mail address is already configured for any of the lists.
Note: Since the domain-part of the address – that is the part after the @ sign – is fixed as part of the System Settings at the Central Administration, we can only set the e-mail alias – the part before the @ sign – for the lists.
Without this capability, the only option is the trial and error method that means we try to assign the mail address from code, and call the Update method of SPList as illustrated below:
SPList list = web.Lists[listName];
list.EmailAlias = "MailAlias"; // the part of the e-mail address before the @ sign
In the case the alias is already reserved for another list, we receive an SPException (Unable to assign this e-mail address to the list, because the address is in use.) that we could optionally handle using a try/catch block.
As you may know using this kind of error handling structure for checking existing items does not perform well, so if there is a great chance for conflicting mail addresses, it would be far better (and faster) to make the check without exceptions.
Let’s see what happens when we try to save the list configuration either from the UI or by custom code.
First, the Update(bool bFromMigration) method of the SPList is called, that calls the AssignAlias(string alias, SPList list) method of the SPEmailMap class. It validates the format of the alias via the static ValidateAlias(string alias) method, and then check the existence of a list having this alias through the CanGetListFromDatabase(string alias) method. This method uses another method GetEmailAliasRecordFromDatabase(string alias) that access the SharePoint database and returns list information in the form of an EmailAliasRecord object.
Note: the e-mail addresses used for this kind of check are stored in the EmailEnabledLists table (with fields Alias, Deleted, SiteId, WebId, ListId) of the configuration database SharePoint. The stored procedure used to get the list data based on the alias is the proc_getEmailEnabledListByAlias.
In the following code, I illustrate how to call the CanGetListFromDatabase method to check the existence of an alias.
Note: the code below uses non-public API calls and so it is not a supported approach. Use this sample at you own risk and preferably only in test environments.