yet another Tcl mail handler! (for UNIX)

Phil Ehrens

Description:

Uses one of three common UNIX mail clients to return e-mail to a user regarding job status or results.

Parameters:

to - the user's e-mail address
subject - the subject line to include in the header
body - the text of the message OR filename(s) to attach
attach - a list of attachments

Comments:

  • Supports attachments if Mutt or Pine are available on the system.
  • Note the two methods of attachment: a comma or space delimited list of files making up the entire body, or a list provided as a fourth argument to the procedure.

The code:

 proc mailTo { { to "" } { subject "" } { body "" } { attach "" } } {

     if { [ string match $to $subject ] } {
        return -code error "mailTo: missing required arguments"
        }

     set attachment {}
     if { [ llength $attach ] } {
        foreach filename $attach {
           if { [ file exists $filename ] } {
              append attachment "-a $filename "
              }
           }
        } else {   
        foreach filename [ split $body " ," ] {
           if { ! [ file exists $filename ] } {
              set attachment {}
              break;
              } else {
              append attachment "-a $filename "
              }
           }
        }   

     foreach agent { mutt pine mailx } {
        if { [ string length [ auto_execok $agent ] ] } {
           switch $agent {
               mailx {
                     if { [ string length $attachment ] } {
                        return -code error "mailTo: no mail agent supporting attachments found"
                        }
                     set mailpipe [ open "| $agent -s $subject $to" w ]
                     break;
                     }
             default {
                     set mailpipe [ open "| $agent -s $subject $attachment $to" w ]
                     break;
                     }
                } ;## end of switch
            } ;## end of if 
        } ;## end of foreach 
     if { ! [ info exists mailpipe ] } {
        return -code error "mailTo: no usable mail agent found on system"
        }
     if { [ catch {
        puts $mailpipe $body
        close $mailpipe
        } err ] } {
        return -code error "mailTo: $err"
        }
     return {}
 }

JOB See as well A tcllib based smtp mailer package for a pure tcl solution.