Example 5: Sending mails through an SMTP server

MAIN
    DEFINE mc base.Channel
    DEFINE i, res INTEGER
    DEFINE subject, emFrom, emRcpt, msg STRING
    DEFINE mailbody DYNAMIC ARRAY OF STRING
    LET subject = "Hello..."
    LET emFrom = "ted.fisher@4js.com"
    LET emRcpt = "ted.fisher@4js.com"
    LET mailbody[1] = "Hello,"
    LET mailbody[2] = "What's new?"
    LET mc = base.Channel.create()
    -- We use channel binary mode to avoid CR+LF translation on Windows.
    -- In text mode, each line would be terminated by \r\r\n on Windows.
    CALL mc.openClientSocket("mail.strasbourg.4js.com", 25, "ub", 5)
    CALL readSmtpAnswer(mc) RETURNING res, msg
    CALL smtpSend(mc, "HELO xxx\r") RETURNING res, msg
    CALL smtpSend(mc, SFMT("MAIL FROM: %1\r", emFrom)) RETURNING res, msg
    CALL smtpSend(mc, SFMT("RCPT TO: %1\r", emRcpt)) RETURNING res, msg
    CALL smtpSend(mc, "DATA\r") RETURNING res, msg
    DISPLAY "Sending mail body:"
    CALL mc.writeLine(SFMT("Subject: %1\r", subject))
    FOR i = 1 TO mailbody.getLength()
        CALL mc.writeLine(mailbody[i])
    END FOR
    CALL mc.writeLine(".")
    CALL readSmtpAnswer(mc) RETURNING res, msg
    DISPLAY "  Result: ", res
    CALL smtpSend(mc, "QUIT\r") RETURNING res, msg
    CALL mc.close()
END MAIN

FUNCTION smtpSend(ch, command)
    DEFINE ch base.Channel
    DEFINE command, msg STRING
    DEFINE res INTEGER
    DISPLAY "Sending command: ", command
    CALL ch.writeLine(command)
    CALL readSmtpAnswer(ch) RETURNING res, msg
    DISPLAY "  Result: ", res
    RETURN res, msg
END FUNCTION

FUNCTION readSmtpAnswer(ch)
    DEFINE ch base.Channel
    DEFINE line, msg STRING
    DEFINE res INTEGER
    LET msg = ""
    WHILE TRUE
        LET line = ch.readLine() -- Note: /r/n is already removed!
        IF line IS NULL THEN
            RETURN -1, "COULD NOT READ SMTP ANSWER"
        END IF
        IF line MATCHES "[0-9][0-9][0-9] *" THEN
            IF msg.getLength() != 0 THEN
                LET msg=msg || "\n"
            END IF
            LET msg=msg.append(line.subString(4, line.getLength()))
            LET res = line.subString(1,3)
            RETURN res, msg
        END IF
        IF line MATCHES "[0-9][0-9][0-9]-*" THEN
            IF msg.getLength() != 0 THEN
                LET msg=msg || "\n"
            END IF
            LET msg=msg.append(line.subString(4, line.getLength()))
        END IF
    END WHILE
END FUNCTION