Pastey simple smtp client
- Posted by jimcbrown
(admin)
Jun 18, 2014
--****
-- === smtp.ex
--
-- Simple example of how to send email via smtp.
--
object _ = 0
without warning
include std/console.e
include std/socket.e as sock
-- user editable parameters start
constant SMTP_HOST = "127.0.0.1"
constant MY_NAME = "example.com"
constant MY_EMAIL = "me@example.com"
constant SEND_TO = "you@example.com"
-- user editable parameters end
-- normally, you don't need to change this
-- some email providers offer alternative ports.
-- fastmail.fm used to offer port 26 for those whose ISPs blocked port 25
-- if port 25 doesn't work, an alternative is to try port 587
constant SMTP_PORT = "25"
--**
--@nodoc@
override procedure abort(integer x)
maybe_any_key()
eu:abort(x)
end procedure
sock:socket sock = sock:create(sock:AF_INET, sock:SOCK_STREAM, 0)
if sock:connect(sock, SMTP_HOST&":"&SMTP_PORT) != sock:OK then
printf(1, "Could not connect to smtp server, is it running?\nError = %d\n",
{ sock:error_code() })
abort(1)
end if
integer level_250 = 0
while 1 do
sequence data = sock:receive(sock, 0)
if match("220", data) then
sock:send(sock, "HELO " & MY_NAME & "\r\n", 0)
elsif match("Hello", data) then
sock:send(sock, "MAIL FROM: <" & MY_EMAIL & ">\r\n", 0)
elsif match("250", data) and level_250 = 0 then
sock:send(sock, "RCPT TO: <" & SEND_TO & ">\r\n", 0)
level_250 = 1
elsif match("250", data) and level_250 = 1 then
Sock:send(sock, "DATA\r\n", 0)
level_250 = 2
elsif match("354", data) then
sock:send(sock, "From: <" & MY_EMAIL & ">\r\n", 0)
sock:send(sock, "To: <" & SEND_TO & ">\r\n", 0)
sock:send(sock, "Date: " & SEND_TO & "\r\n", 0)
sock:send(sock, "Subject: test email\r\n", 0)
sock:send(sock, "\r\n", 0)
sock:send(sock, "test data\r\n", 0)
sock:send(sock, "extra lines here\r\n", 0)
sock:send(sock, "\r\n", 0)
sock:send(sock, ".\r\n", 0) -- signal to smtpd server that we're finished writing the email, so send it now.
elsif match("250", data) and level_250 = 2 then
sock:send(sock, "quit\r\n", 0)
exit
end if
end while
sock:close(sock)