Search code examples
asp.netvb.netemailwindows-authenticationsmtpclient

System.Net.Mail.SmtpClient - Client does not have permission to send as this sender


I have a need to send an email via a web application but the address that the email goes to requires SMTP authentication. The code works for mailboxes that don't need authentication.

I would like to pass across Windows user credentials (the site uses Windows authentication) and thought this would be achieved with my code, but unfortunately I get errors about the client not having permission to send. I'm assuming it is using the credentials of the application pool user rather than the logged in user.

Dim mailMessage As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage()
mailMessage.IsBodyHtml = True
Dim strBody As String = "<font size='2' font face='Tahoma'>" & _
"<br><br><b>Date: </b>" & Me.txtDate.Text
mailMessage.From = New System.Net.Mail.MailAddress(fromAddress) 'Logged in user's email address
' More code here to build the email body etc... 
' Then attempt to send it:
Dim smtpClient As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient
smtpClient.UseDefaultCredentials = True
smtpClient.Send(mailMessage)

Web.config contains only the SMTP server name under system.net (mailsettings->smtp)

How do I get the application to use the user's credentials?


Solution

  • Did you specify the UseDefaultCredentials in the Web.config? If not you must do that to use them. This will allow the currently logged in user to send email trough the specified SMTP server. Note that websites usually run under a separate user credential, not the currently logged in user on the machine.

    <system.net>
      <mailSettings>
        <smtp deliveryMethod="network">
          <network host="localhost" port="25" defaultCredentials="true" />
        </smtp>
      </mailSettings>
    </system.net>
    

    Or specify the credentials in code.

    smtpClient.Credentials = new NetworkCredential("[email protected]", "abcd1234");
    

    If both do not work you simply are not authorized to send mail on that server.

    See for more info

    https://msdn.microsoft.com/nl-nl/library/system.net.mail.smtpclient.usedefaultcredentials(v=vs.110).aspx

    https://msdn.microsoft.com/nl-nl/library/w355a94k(v=vs.110).aspx