Establishing a Connection

Before mail can be sent or retrieved, a connection must be established with an email server. This is done using the Winsock control’s Connect method, as shown here:

Winsock1.Connect "mail.execpc.com", 25

The arguments to this method are the address of the email server and the port on which to request connection. The fact that this code fragment requests connection on port 25 tells the server that the client is interested in using the SMTP protocol for sending email. A request to use the POP3 protocol to retrieve email uses port 110, as shown here:

Winsock1.Connect "mail.execpc.com", 110

The Connect method is asynchronous. That is, it returns control to the next line of Visual Basic code even before the connection is established. When the connection does become established, the Winsock control raises the Connect event and sets the value of the control’s State property to sckConnected. It is an error to send SMTP or POP3 commands before the connection is established.

The TCP connection can be closed either by the client or by the server. To close it from the client side, call the Winsock control’s Close method, as shown here:

Winsock1.Close

Finally, if the connection is closed by the server, the Winsock control raises a Close event, as shown here:

Private Sub Winsock1_Close( )
   ' Place any cleanup code here.
End Sub ' Winsock1_Close

This asynchronous mechanism of communication makes programming the Winsock control more complicated than other email mechanisms, but ...

Get CDO & MAPI Programming with Visual Basic: now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.