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

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

Establish a connection to the specified IMAP or IMAP/S server using the provided socket.

Establishes a connection to the specified IMAP or IMAP/S server using the provided socket.

If the port has a value of 0, then the options parameter is used to determine the default port to connect to. The default port used with SecureSocketOptions.SslOnConnect is 993. All other values will use a default port of 143.

If the options has a value of SecureSocketOptions.Auto, then the port is used to determine the default security options. If the port has a value of 993, then the default options used will be SecureSocketOptions.SslOnConnect. All other values will use SecureSocketOptions.StartTlsWhenAvailable.

Once a connection is established, properties such as AuthenticationMechanisms and Capabilities will be populated.

/// is null. /// -or- /// is null. /// /// is not between 0 and 65535. /// /// is not connected. /// -or- /// The is a zero-length string. /// /// The has been disposed. /// /// The is already connected. /// /// was set to /// /// and the IMAP server does not support the STARTTLS extension. /// /// The operation was canceled via the cancellation token. /// /// An I/O error occurred. /// /// An IMAP protocol error occurred. ///
public Connect ( Socket socket, string host, int port, SecureSocketOptions options = SecureSocketOptions.Auto, CancellationToken cancellationToken = default(CancellationToken) ) : void
socket Socket The socket to use for the connection.
host string The host name to connect to.
port int The port to connect to. If the specified port is 0, then the default port will be used.
options SecureSocketOptions The secure socket options to when connecting.
cancellationToken System.Threading.CancellationToken The cancellation token.
Результат void
		public void Connect (Socket socket, string host, int port = 0, SecureSocketOptions options = SecureSocketOptions.Auto, CancellationToken cancellationToken = default (CancellationToken))
		{
			if (socket == null)
				throw new ArgumentNullException (nameof (socket));

			if (!socket.Connected)
				throw new ArgumentException ("The socket is not connected.", nameof (socket));

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

			if (host.Length == 0)
				throw new ArgumentException ("The host name cannot be empty.", nameof (host));

			if (port < 0 || port > 65535)
				throw new ArgumentOutOfRangeException (nameof (port));

			CheckDisposed ();

			if (IsConnected)
				throw new InvalidOperationException ("The ImapClient is already connected.");
			
			Stream stream;
			bool starttls;
			Uri uri;

			ComputeDefaultValues (host, ref port, ref options, out uri, out starttls);

			engine.Uri = uri;

			if (options == SecureSocketOptions.SslOnConnect) {
				var ssl = new SslStream (new NetworkStream (socket, true), false, ValidateRemoteCertificate);

				try {
#if COREFX
					ssl.AuthenticateAsClientAsync (host, ClientCertificates, SslProtocols, true).GetAwaiter ().GetResult ();
#else
					ssl.AuthenticateAsClient (host, ClientCertificates, SslProtocols, true);
#endif
				} catch {
					ssl.Dispose ();
					throw;
				}

				secure = true;
				stream = ssl;
			} else {
				stream = new NetworkStream (socket, true);
				secure = false;
			}

			if (stream.CanTimeout) {
				stream.WriteTimeout = timeout;
				stream.ReadTimeout = timeout;
			}

			ProtocolLogger.LogConnect (uri);

			engine.Connect (new ImapStream (stream, socket, ProtocolLogger), cancellationToken);

			try {
				// Only query the CAPABILITIES if the greeting didn't include them.
				if (engine.CapabilitiesVersion == 0)
					engine.QueryCapabilities (cancellationToken);
				
				if (options == SecureSocketOptions.StartTls && (engine.Capabilities & ImapCapabilities.StartTLS) == 0)
					throw new NotSupportedException ("The IMAP server does not support the STARTTLS extension.");
				
				if (starttls && (engine.Capabilities & ImapCapabilities.StartTLS) != 0) {
					var ic = engine.QueueCommand (cancellationToken, null, "STARTTLS\r\n");

					engine.Wait (ic);

					ProcessResponseCodes (ic);

					if (ic.Response == ImapCommandResponse.Ok) {
						var tls = new SslStream (stream, false, ValidateRemoteCertificate);
#if COREFX
						tls.AuthenticateAsClientAsync (host, ClientCertificates, SslProtocols, true).GetAwaiter ().GetResult ();
#else
						tls.AuthenticateAsClient (host, ClientCertificates, SslProtocols, true);
#endif
						engine.Stream.Stream = tls;

						secure = true;

						// Query the CAPABILITIES again if the server did not include an
						// untagged CAPABILITIES response to the STARTTLS command.
						if (engine.CapabilitiesVersion == 1)
							engine.QueryCapabilities (cancellationToken);
					} else if (options == SecureSocketOptions.StartTls) {
						throw ImapCommandException.Create ("STARTTLS", ic);
					}
				}
			} catch {
				engine.Disconnect ();
				secure = false;
				throw;
			}

			engine.Disconnected += OnEngineDisconnected;
			OnConnected ();
		}
#endif

Same methods

ImapClient::Connect ( string host, int port, SecureSocketOptions options = SecureSocketOptions.Auto, CancellationToken cancellationToken = default(CancellationToken) ) : void

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::Connect