Expect SMTP Script

The following expect script will connect to a mailserver and attempt to send a test message. Useful for quickly troubleshooting mail issues.

Usage: expect mail.exp mailserver from_address to_address

#!/usr/bin/expect
set mailserver [lrange $argv 0 0]
set from [lrange $argv 1 1]
set to [lrange $argv 2 2]

spawn telnet $mailserver 25
expect "failed" {
send_user "$mailserver: connect failed\n"
exit
} "2?? *" {
} "4?? *" {
exit
} "refused" {
send_user "$mailserver: connect refused\n"
exit
} "closed" {
send_user "$mailserver: connect closed\n"
exit
} timeout {
send_user "$mailserver: connect to port 25 timeout\n"
exit
}
send "HELO foo.com\r"
expect "2?? *" {
} "5?? *" {
exit
} "4?? *" {
exit
}
send "MAIL FROM: <$from>\r"
expect "2?? *" {
} "5?? *" {
exit
} "4?? *" {
exit
}
send "RCPT TO: <$to>\r"
expect "2?? *" {
} "5?? *" {
exit
} "4?? *" {
exit
}
send "DATA\r"
expect "3?? *" {
} "5?? *" {
exit
} "4?? *" {
exit
}
send "From: $from\r"
send "To: $to\r"
send "Subject: test\r"
send "This is a test message\r"
send ".\r"
expect "2?? *" {
} "5?? *" {
exit
} "4?? *" {
exit
}
send "QUIT\r"
exit

Bitbucket snippet: https://bitbucket.org/snippets/pvibert/ye7eE6