MailKit.Net.Imap.ImapClient.Authenticate C# (CSharp) Метод

Authenticate() публичный Метод

Authenticate using the supplied credentials.

If the IMAP server supports one or more SASL authentication mechanisms, 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 the server does not support SASL or if no common SASL mechanisms can be found, then LOGIN command is used as a fallback.

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 has been disposed. /// /// The is not connected. /// /// The is already authenticated. /// /// 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. /// /// An IMAP 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.
Результат 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 ();
			CheckConnected ();

			if (engine.State >= ImapEngineState.Authenticated)
				throw new InvalidOperationException ("The ImapClient is already authenticated.");

			int capabilitiesVersion = engine.CapabilitiesVersion;
			var uri = new Uri ("imap://" + engine.Uri.Host);
			NetworkCredential cred;
			ImapCommand ic = null;
			SaslMechanism sasl;
			string id;

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

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

				cancellationToken.ThrowIfCancellationRequested ();

				var command = string.Format ("AUTHENTICATE {0}", sasl.MechanismName);

				if ((engine.Capabilities & ImapCapabilities.SaslIR) != 0 && sasl.SupportsInitialResponse) {
					var ir = sasl.Challenge (null);
					command += " " + ir + "\r\n";
				} else {
					command += "\r\n";
				}

				ic = engine.QueueCommand (cancellationToken, null, command);
				ic.ContinuationHandler = (imap, cmd, text) => {
					string challenge;

					if (sasl.IsAuthenticated) {
						// The server claims we aren't done authenticating, but our SASL mechanism thinks we are...
						// Send an empty string to abort the AUTHENTICATE command.
						challenge = string.Empty;
					} else {
						challenge = sasl.Challenge (text);
					}

					var buf = Encoding.ASCII.GetBytes (challenge + "\r\n");
					imap.Stream.Write (buf, 0, buf.Length, cmd.CancellationToken);
					imap.Stream.Flush (cmd.CancellationToken);
				};

				engine.Wait (ic);

				if (ic.Response != ImapCommandResponse.Ok) {
					for (int i = 0; i < ic.RespCodes.Count; i++) {
						if (ic.RespCodes[i].Type != ImapResponseCodeType.Alert)
							continue;

						OnAlert (ic.RespCodes[i].Message);

						throw new AuthenticationException (ic.ResponseText ?? ic.RespCodes[i].Message);
					}

					continue;
				}

				engine.State = ImapEngineState.Authenticated;

				cred = credentials.GetCredential (uri, sasl.MechanismName);
				id = GetSessionIdentifier (cred.UserName);
				if (id != identifier) {
					engine.FolderCache.Clear ();
					identifier = id;
				}

				// Query the CAPABILITIES again if the server did not include an
				// untagged CAPABILITIES response to the AUTHENTICATE command.
				if (engine.CapabilitiesVersion == capabilitiesVersion)
					engine.QueryCapabilities (cancellationToken);

				engine.QueryNamespaces (cancellationToken);
				engine.QuerySpecialFolders (cancellationToken);
				OnAuthenticated (ic.ResponseText);
				return;
			}

			if ((Capabilities & ImapCapabilities.LoginDisabled) != 0) {
				if (ic == null)
					throw new AuthenticationException ("The LOGIN command is disabled.");

				throw CreateAuthenticationException (ic);
			}

			// fall back to the classic LOGIN command...
			cred = credentials.GetCredential (uri, "DEFAULT");

			ic = engine.QueueCommand (cancellationToken, null, "LOGIN %S %S\r\n", cred.UserName, cred.Password);

			engine.Wait (ic);

			ProcessResponseCodes (ic);

			if (ic.Response != ImapCommandResponse.Ok)
				throw CreateAuthenticationException (ic);

			engine.State = ImapEngineState.Authenticated;

			id = GetSessionIdentifier (cred.UserName);
			if (id != identifier) {
				engine.FolderCache.Clear ();
				identifier = id;
			}

			// Query the CAPABILITIES again if the server did not include an
			// untagged CAPABILITIES response to the LOGIN command.
			if (engine.CapabilitiesVersion == capabilitiesVersion)
				engine.QueryCapabilities (cancellationToken);

			engine.QueryNamespaces (cancellationToken);
			engine.QuerySpecialFolders (cancellationToken);
			OnAuthenticated (ic.ResponseText);
		}

Usage Example

Пример #1
2
        public ActionResult Index(int currentPageNumber, int nextPageNumber)
        {
            int startSerialNumber = ((nextPageNumber - 1) * 30) + 1;
            int endSerialNumber = ((nextPageNumber) * 30);

            List<Email> emails = new List<Email>();

            try
            {

                userGmailConfig = FetchUserGmailProfile();
                using (ImapClient client = new ImapClient())
                {
                    client.Connect(userGmailConfig.IncomingServerAddress, userGmailConfig.IncomingServerPort, true);
                    client.Authenticate(new NetworkCredential(userGmailConfig.GmailUsername, userGmailConfig.GmailPassword));

                    var inbox = client.Inbox;
                    inbox.Open(FolderAccess.ReadOnly);

                    if (inbox.Count > 0)
                    {
                        int pageEndIndex = Math.Max(inbox.Count - startSerialNumber, 0);
                        int pageStartIndex = Math.Max(inbox.Count - endSerialNumber, 0);

                        var messages = inbox.Fetch(pageStartIndex, pageEndIndex, MessageSummaryItems.Envelope);

                        messages = messages.OrderByDescending(message => message.Envelope.Date.Value.DateTime).ToList();

                        foreach (var message in messages)
                        {
                            if (startSerialNumber <= endSerialNumber)
                            {
                                Email tempEmail = new Email()
                                {
                                    SerialNo = startSerialNumber,
                                    Uid = message.UniqueId,
                                    FromDisplayName = message.Envelope.From.First().Name,
                                    FromEmail = message.Envelope.From.First().ToString(),
                                    To = message.Envelope.To.ToString(),
                                    Subject = message.NormalizedSubject,
                                    TimeReceived = message.Envelope.Date.Value.DateTime,
                                    HasAttachment = message.Attachments.Count() > 0 ? true : false
                                };
                                emails.Add(tempEmail);
                                startSerialNumber++;
                            }
                        }
                    }
                }

                ViewBag.EmailId = userGmailConfig.GmailUsername;
                ViewBag.NoOfEmails = endSerialNumber;
                if (currentPageNumber > nextPageNumber)
                {
                    ViewBag.PageNumber = currentPageNumber - 1;
                }
                else
                {
                    ViewBag.PageNumber = currentPageNumber + 1;
                }
            }
            catch (Exception ex)
            {
                ViewBag.ErrorMessage = "There was an error in processing your request. Exception: " + ex.Message;
            }

            return View(emails);
        }
All Usage Examples Of MailKit.Net.Imap.ImapClient::Authenticate