MailKit проблем с отправкой письм - 5.7.60 SMTP; Client does not have permissions to send as this sender

Пытаюсь написать приложение, в котором будет происходить отправка письм, с уже заранее заданым текстом и отправителями.

Для тестирования, написал мини приложение, которое из Active Directory вытаскивает Email отправителя, аутифицируется через NSspi и отправляет письмо. Отправка происходит через MailKit

Собственно мой примерный код отправки:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim emailMessage = New MimeMessage()
emailMessage.From.Add(New MailboxAddress(UserPrincipal.Current.Name, UserPrincipal.Current.EmailAddress))

emailMessage.To.Add(New MailboxAddress("", "[email protected]"))
emailMessage.Cc.Add(New MailboxAddress(UserPrincipal.Current.Name, UserPrincipal.Current.EmailAddress))

emailMessage.Subject = "Test Mail: Test"
Dim emailBuilder As New BodyBuilder()

emailBuilder.HtmlBody = String.Format("<div>Hi, <br/><br/><br/><br/> 
                                          ___________________________________________________________________
                                          <br/><br/>+++ TEST EMAIL +++<br/>
                                          ___________________________________________________________________<br/><br/>
                                          ")

' Now we just need to set the message body and we're done
emailMessage.Body = emailBuilder.ToMessageBody()

Using emailClient = New SmtpClient()
  emailClient.Connect("smtp-server.com", 587, SecureSocketOptions.None)

  If emailClient.Capabilities.HasFlag(SmtpCapabilities.Authentication) Then
    Dim sasl As SaslMechanismNtlmIntegrated = New SaslMechanismNtlmIntegrated()
    emailClient.Authenticate(sasl)
  End If

  If emailClient.Capabilities.HasFlag(SmtpCapabilities.Size) Then
    Console.WriteLine("The SMTP server has a size restriction on messages: {0}.", emailClient.MaxSize)
  End If

  If emailClient.Capabilities.HasFlag(SmtpCapabilities.Dsn) Then
    Console.WriteLine("The SMTP server supports delivery-status notifications.")
  End If

  If emailClient.Capabilities.HasFlag(SmtpCapabilities.EightBitMime) Then
    Console.WriteLine("The SMTP server supports Content-Transfer-Encoding: 8bit")
  End If

  If emailClient.Capabilities.HasFlag(SmtpCapabilities.BinaryMime) Then
    Console.WriteLine("The SMTP server supports Content-Transfer-Encoding: binary")
  End If

  If emailClient.Capabilities.HasFlag(SmtpCapabilities.UTF8) Then
    Console.WriteLine("The SMTP server supports UTF-8 in message headers.")
  End If

  emailClient.Send(emailMessage)
  emailClient.Disconnect(True)
End Using

End Sub

и класс SaslMechanismNtlmIntegrated

Imports MailKit.Security
Imports NSspi
Imports NSspi.Contexts
Imports NSspi.Credentials

Public Class SaslMechanismNtlmIntegrated
  Inherits SaslMechanism

  Enum LoginState
    Initial
    Challenge
  End Enum

  Private state As LoginState
  Private sspiContext As ClientContext

  Public Sub New()
    MyBase.New(String.Empty, String.Empty)
  End Sub

  Public Overrides ReadOnly Property MechanismName As String
    Get
      Return "NTLM"
    End Get
  End Property

  Public Overrides ReadOnly Property SupportsInitialResponse As Boolean
    Get
      Return True
    End Get
  End Property

  Protected Overrides Function Challenge(ByVal token As Byte(), ByVal startIndex As Integer, ByVal length As Integer) As Byte()
    If IsAuthenticated Then Throw New InvalidOperationException()
    InitializeSSPIContext()
    Dim serverResponse As Byte() = Nothing
    Dim status As SecurityStatus

    Select Case state
      Case LoginState.Initial
        status = sspiContext.Init(Nothing, serverResponse)
        state = LoginState.Challenge
      Case LoginState.Challenge
        status = sspiContext.Init(token, serverResponse)
        IsAuthenticated = True
      Case Else
        Throw New IndexOutOfRangeException("state")
    End Select

    Return serverResponse
  End Function

  Private Sub InitializeSSPIContext()
    If sspiContext IsNot Nothing Then
      Return
    End If

    Dim credential = New ClientCurrentCredential(PackageNames.Ntlm)
    sspiContext = New ClientContext(credential, String.Empty, ContextAttrib.InitIntegrity Or ContextAttrib.ReplayDetect Or ContextAttrib.SequenceDetect Or ContextAttrib.Confidentiality)
  End Sub

  Public Overrides Sub Reset()
    state = LoginState.Initial
    MyBase.Reset()
  End Sub
End Class

При отправки письма получаю следующую ошибку 5.7.60 SMTP; Client does not have permissions to send as this sender. Не понимаю в чем проблема, ведь аутификация происходит именно через пользователя, который сидит перед компьютером и вошел в свой аккаунт.


Ответы (3 шт):

Автор решения: 0x00x

У вас либо анонимная отправка идёт, либо логин и имя отправителя не совпадают.

→ Ссылка
Автор решения: Vlad

Подозрительно что порт 587 и SecureSocketOptions.None. Без TLS порт обычно 25. А если у вас TLS то и нужно указывать что-то в духе SecureSocketOptions.StartTls

→ Ссылка
Автор решения: Olga Mukhamatova

В моем случае эта ошибка возникла из-за того, что был указан как "Send As" другой email адрес, а в настройках почтового сервера не было прав на отправку от другого отправителя.

This error indicates a configuration issue on the Microsoft Exchange Server due to a missing "Send As" permission for the user. https://forums.ivanti.com/s/article/Error-While-Attempting-to-Send-Email-Using-Smtp-5-7-60-Smtp-Client-Does-Not-Have-Permissions-to-Send-as-This-Sender?language=en_US

→ Ссылка