MailKit.Net.Smtp.SmtpClient.Authenticate C# (CSharp) Method

Authenticate() public method

Authenticates using the supplied credentials.

If the SMTP server supports authentication, then the SASL mechanisms that both the client and server support are tried in order of greatest security to weakest security. Once a SASL authentication mechanism is found that both client and server support, the credentials are used to authenticate.

If, on the other hand, authentication is not supported by the SMTP server, then this method will throw System.NotSupportedException. The Capabilities property can be checked for the SmtpCapabilities.Authentication flag to make sure the SMTP server supports authentication before calling this method.

To prevent the usage of certain authentication mechanisms, simply remove them from the AuthenticationMechanisms hash set before calling this method.
/// is null. /// -or- /// is null. /// /// The is not connected. /// /// The is already authenticated. /// /// The SMTP server does not support authentication. /// /// The operation was canceled via the cancellation token. /// /// Authentication using the supplied credentials has failed. /// /// A SASL authentication error occurred. /// /// An I/O error occurred. /// /// The SMTP command failed. /// /// An SMTP protocol error occurred. ///
public Authenticate ( Portable.Text.Encoding encoding, ICredentials credentials, CancellationToken cancellationToken = default(CancellationToken) ) : void
encoding Portable.Text.Encoding The text encoding to use for the user's credentials.
credentials ICredentials The user's credentials.
cancellationToken System.Threading.CancellationToken The cancellation token.
return void
		public override void Authenticate (Encoding encoding, ICredentials credentials, CancellationToken cancellationToken = default (CancellationToken))
		{
			if (encoding == null)
				throw new ArgumentNullException (nameof (encoding));

			if (credentials == null)
				throw new ArgumentNullException (nameof (credentials));

			CheckDisposed ();

			if (!IsConnected)
				throw new ServiceNotConnectedException ("The SmtpClient must be connected before you can authenticate.");

			if (IsAuthenticated)
				throw new InvalidOperationException ("The SmtpClient is already authenticated.");

			if ((capabilities & SmtpCapabilities.Authentication) == 0)
				throw new NotSupportedException ("The SMTP server does not support authentication.");

			var uri = new Uri ("smtp://" + host);
			AuthenticationException authException = null;
			SmtpResponse response;
			SaslMechanism sasl;
			bool tried = false;
			string challenge;
			string command;

			foreach (var authmech in SaslMechanism.AuthMechanismRank) {
				if (!AuthenticationMechanisms.Contains (authmech))
					continue;

				if ((sasl = SaslMechanism.Create (authmech, uri, encoding, credentials)) == null)
					continue;

				tried = true;

				cancellationToken.ThrowIfCancellationRequested ();

				// send an initial challenge if the mechanism supports it
				if (sasl.SupportsInitialResponse) {
					challenge = sasl.Challenge (null);
					command = string.Format ("AUTH {0} {1}", authmech, challenge);
				} else {
					command = string.Format ("AUTH {0}", authmech);
				}

				response = SendCommand (command, cancellationToken);

				if (response.StatusCode == SmtpStatusCode.AuthenticationMechanismTooWeak)
					continue;

				SaslException saslException = null;

				try {
					while (!sasl.IsAuthenticated) {
						if (response.StatusCode != SmtpStatusCode.AuthenticationChallenge)
							throw new SmtpCommandException (SmtpErrorCode.UnexpectedStatusCode, response.StatusCode, response.Response);

						challenge = sasl.Challenge (response.Response);
						response = SendCommand (challenge, cancellationToken);
					}

					saslException = null;
				} catch (SaslException ex) {
					// reset the authentication state
					response = SendCommand (string.Empty, cancellationToken);
					saslException = ex;
				}

				if (response.StatusCode == SmtpStatusCode.AuthenticationSuccessful) {
					if (QueryCapabilitiesAfterAuthenticating)
						Ehlo (cancellationToken);
					authenticated = true;
					OnAuthenticated (response.Response);
					return;
				}

				var message = string.Format ("{0}: {1}", response.StatusCode, response.Response);

				if (saslException != null)
					authException = new AuthenticationException (message, saslException);
				else
					authException = new AuthenticationException (message);
			}

			if (tried)
				throw authException ?? new AuthenticationException ();

			throw new NotSupportedException ("No compatible authentication mechanisms found.");
		}

Usage Example

Example #1
3
        public void Send(EmailDependencies email)
        {
            try
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress(email.FromName, email.FromAddress));

                message.To.Add(new MailboxAddress(email.ToName, email.ToAddress));
                message.To.Add(new MailboxAddress(email.FromName, email.FromAddress));

                message.Subject = email.Title;
                message.Body = new TextPart("html") { Text = email.content };

                using (var client = new SmtpClient())
                {
                    client.Connect("mail.bizmonger.net", 587, false);

                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    // Note: only needed if the SMTP server requires authentication
                    client.Authenticate(Configuration.ServerEmail, Configuration.Password);

                    client.Send(message);
                    client.Disconnect(true);
                }
            }
            catch (Exception ex)
            {
                var errorMessage = ex.GetBaseException().Message;
                Debug.WriteLine(errorMessage);
            }
        }
All Usage Examples Of MailKit.Net.Smtp.SmtpClient::Authenticate