Search code examples
c#asp.netcredentialshttpcontextsmtpclient

How can I use the HttpContext.Current.User.Identity to provide authentication to my SmtpClient.Credentials?


I have a weird situation.

In my website, I impersonate a lab account for access to a database, but for the front-end, I allow Windows authentication. So that means HttpContext.Current.User.Identity.Name.Split('\')1 gives me the name of the user viewing the site so I can print a welcome message, but something like Environment.Username will give me 'labaccount'.

Just to be clear, on the server's IIS Manager --> Basic Settings --> Connect as... = labaccount username/password, and in the site's web.config:

<configuration>
  <connectionStrings>
    <add name="DatabaseConnectionString" connectionString="blahblahblah" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <compilation debug="false" targetFramework="4.0" />
    <customErrors mode="Off" />
     <identity impersonate="true" />
</system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
  </system.webServer>

</configuration>

Now on the website, I need a way to send an email to a set of people, except the sender needs to be the user viewing the site and not the lab account. When I set the sender in 'mailFrom' to the lab account, everything works as expected, but when I change it to HttpContext.Current.User, I get an error saying 'Mailbox unavailable. The server response was: 5.7.1 Client does not have permissions to send as this sender'. Here's the part of my code that sends the email:

MailMessage mail = new MailMessage(mailFrom, mailTo, subject, null);
mail.IsBodyHtml = true;
mail.Body += mailBody;
SmtpClient smtpClient = new SmtpClient("smtphost");
smtpClient.Credentials = CredentialCache.DefaultNetworkCredentials;
smtpClient.Send(mail);

This doesn't work, so I tried doing something like this, based on what I saw here:

MailMessage mail = new MailMessage(mailFrom, mailTo, subject, null);
mail.IsBodyHtml = true;
mail.Body += mailBody;
SmtpClient smtpClient = new SmtpClient("smtphost");
smtpClient.UseDefaultCredentials = false;
WindowsImpersonationContext impersonationContext;
impersonationContext = ((WindowsIdentity)HttpContext.Current.User.Identity).Impersonate();
smtpClient.Send(mail);
impersonationContext.Undo();

This didn't work either. I'm at a loss here. Is it even possible to use this approach? What else can I try?


Solution

  • Apparently, this cannot be done. I worked around it by launching a compose window in Outlook, and pre-loading the body of the email in HTML.

    http://msdn.microsoft.com/en-us/library/office/aa171418(v=office.11).aspx