Simple Mail Transfer Protocol (SMTP)

One of the easiest high-level TCP protocols to use is SMTP for sending an email message.  This application simply connects to an SMTP server via TCP, identifies itself, and identifies who the message is for, sends the text of the message, and finally says goodbye.  As each line of text is sent to the server, it returns a status code and message to indicate progress.  The following code demonstrates this:

#COMPILE EXE

 

' Be sure to change the following two string equates

' to the name of your SMTP mail server and your email

' address.

 

$mailhost = "mailserver.mydomain.com"

$mailfrom = "email@address.com"

 

FUNCTION PBMAIN() AS LONG

 

  ' Get the local computer's IP address and name

  HOST ADDR TO ip&

  HOST NAME ip& TO hostname$

 

' ** Connect to the mailhost

  hTCP& = FREEFILE

  TCP OPEN "smtp" AT $mailhost AS hTCP&

  IF ERR THEN

    PRINT "Error connecting to mailhost"

    EXIT FUNCTION

  ELSE

    TCP LINE hTCP&, buffer$

    IF LEFT$(buffer$, 3) <> "220" THEN

      PRINT "Mailhost Error: "; buffer$

      EXIT FUNCTION

    END IF

  END IF

 

' ** Greet the mailhost

  TCP PRINT hTCP&, "HELO " + hostname$

  TCP LINE hTCP&, buffer$

  IF LEFT$(buffer$, 3) <> "250" THEN

    PRINT "HELO Error: "; buffer$

    TCP CLOSE hTCP&

    EXIT FUNCTION

  END IF

 

' ** Tell the mailhost who we are

  TCP PRINT hTCP&, "MAIL FROM:<" & $mailfrom & ">"

  TCP LINE hTCP&, buffer$

  IF LEFT$(buffer$, 3) <> "250" THEN

    PRINT "MAIL FROM Error: "; buffer$

    TCP CLOSE hTCP&

    EXIT FUNCTION

  END IF

 

' ** Tell the mailhost who we want to send the message to

  TCP PRINT hTCP&, "RCPT TO:<info@powerbasic.com>"

  TCP LINE hTCP&, buffer$

  IF LEFT$(buffer$, 3) <> "250" THEN

    PRINT "RCPT TO Error: "; buffer$

    TCP CLOSE hTCP&

    EXIT FUNCTION

  END IF

 

' ** Now we can send the message

  TCP PRINT hTCP&, "DATA"

  TCP LINE hTCP&, buffer$

  IF LEFT$(buffer$, 3) <> "354" THEN

    PRINT "DATA Error: "; buffer$

    TCP CLOSE hTCP&

    EXIT FUNCTION

  END IF

 

  TCP PRINT hTCP&, "From: " & $mailfrom

  TCP PRINT hTCP&, "To: info@powerbasic.com"

  TCP PRINT hTCP&, "Subject: Greetings!"

 

  TCP PRINT hTCP&, "Just wanted to say hello."

  TCP PRINT hTCP&, "This TCP stuff is great!

 

' ** End of the message

  TCP PRINT hTCP&, "."

  TCP LINE hTCP&, buffer$

  IF LEFT$(buffer$, 3) <> "250" THEN

    PRINT "DATA Error: "; buffer$

    TCP CLOSE hTCP&

    EXIT FUNCTION

  END IF

 

' ** Say goodbye

  TCP PRINT hTCP&, "QUIT"

  TCP LINE hTCP&, buffer$

  IF LEFT$(buffer$, 3) <> "221" THEN

    PRINT "QUIT Error: "; buffer$

    TCP CLOSE hTCP&

    EXIT FUNCTION

  END IF

 

  TCP CLOSE hTCP&

 

END FUNCTION

The SMTP protocol is fully described in RFC 821 http://www.powerbasic.com/files/pub/docs/rfc/800/rfc821.zip

 

See Also

TCP and UDP Communications

TCP clients and servers

An ECHO client and server using TCP