Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
autodiscover for Outlook, working with hMailServer (and other IMAP, SMTP connections) in C# on IIS
<%@ Page Language="C#" %>
<% Response.ContentType = "text/xml";
Nabil Redmann 2016
reachable through https://autodiscover.DOMAIN.TLD/Autodiscover/Autodiscover.aspx
'-> add a rewrite from Autodiscover.xml to Autodiscover.aspx -> at /web.config
I added a lot of domains (the DOMAIN.TLD part), binded to the physical path of this file. (IIS, would also work with apache aliases)
There is no extra DNS stuff required, we have a subdomain and a path here. (There are also other methods of using the autodiscover handler.)
Needs a valid SSL certificate for this subdomain (SSL is used in the configuration, and Outlook will reject non SSL autodiscover paths)
-> CA Authority 'lets encrypt', and for the lets encrypt clients for IIS an empty index.html to return a response code 200
// *** extract the domain name from the request
string[] s = Request.Url.Host.Split(new char[]{'.'});
string newHost = s[1] + "." + s[0]; // domain.tld
// *** read all of the post data
var sr = new System.IO.StreamReader(Request.InputStream);
string content = sr.ReadToEnd();
// *** save posted XML request
using (var w = new System.IO.StreamWriter(Server.MapPath("~/Autodiscover/cache/data.txt"), true))
w.WriteLine(content); // Write the text
// *** overwrite supplied username with email address for LoginName
// Android trouble ??
string eMail = "";
Regex re = new Regex(@"<EMailAddress>(.*)<\/EMailAddress>");
Match m = re.Match(content);
if (m.Groups.Count > 0)
eMail = "<LoginName>" + m.Groups[1].Value + "</LoginName>";
%><?xml version="1.0" encoding="utf-8" ?>
<Autodiscover xmlns="">
<Response xmlns="">
<%= eMail %>
<Server>imap.<%= newHost %></Server>
<%= eMail %>
<Server>smtp.<%= newHost %></Server>
<?xml version="1.0" encoding="UTF-8"?>
<rewriteMap name="/Autodiscover/Autodiscover.xml">
<add key="/Autodiscover/Autodiscover.xml" value="/Autodiscover/Autodiscover.aspx" />
<rule name="Rewriting to /Autodiscover/Autodiscover.xml">
<match url=".*" />
<add input="{/Autodiscover/Autodiscover.xml:{REQUEST_URI}}" pattern="(.+)" />
<action type="Rewrite" url="{C:1}" appendQueryString="false" />
<httpErrors errorMode="DetailedLocalOnly" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment