Dynamic email attachments

Hi all,

I am quite new to Unix shell scripting and I am trying to create a common function to send mail that is capable of adding multiple attachments. The script works if there is only one attachment. But when there is more than one, it just won't work. It gives a syntax message "Usage: uuencode [-m] [infile] remotefile". Can anyone help what I am doing wrong here? Below is a snippet of the function "func_send_mail" script:

 
 typeset email=$1;
 typeset subject=$2;
 typeset message=$3;
 typeset sourceAttachments=$4;
 
 typeset attachmentString="";
 typeset fileNameIndex="";
 typeset fileNameAttachment="";
 typeset fileAttachmentPath="";
 
 
# loop through the space delimited list of file attachments(with the path)
 for fileAttachmentPath in $sourceAttachments
 do
  # get the filename from the path
  set -A varray `echo "$fileAttachmentPath"| awk '{numberOfFields=split($0,fields,"/")
  for(i=1;i<=numberOfFields;i++)
  print fields}'`
  fileNameIndex=`expr ${#varray
[*]} - 1`
  fileNameAttachment=${varray[$fileNameIndex]}
 
  # assign attachment parameters to this string
  if [ -n "${attachmentString}" ]; 
  then
   attachmentString="$attachmentString; uuencode $fileAttachmentPath $fileNameAttachment";
  else
   attachmentString="uuencode $fileAttachmentPath $fileNameAttachment";
  fi
 done
 
 # send mail with attachments:
 ( echo "${message}"; ${attachmentString} ) | mailx -s "${subject}" "${email}"
 

Below is a sample usage of the function i created:

func_send_mail "testmail@email.com" "Test mail" "This is just a test email" "/home/user/logs/infotask_20110401.log /home/user/logs/infotask_20110402.log /home/user/logs/infotask_20110403.log"

Thanks.

Try this one when sending your mail:

 ( echo "${message}"; eval ${attachmentString} ) | mailx -s "${subject}" "${email}"
1 Like

Needs an "eval" because you are composing a command line then executing that line later. I also needed a "-m" on mailx to get the attachments to be attachments. You may not need this - it depends on what Operating System and version you have (It always helps to state what you have).

(echo "${message}"; eval ${attachmentString}) | mailx -s "${subject}" "${email}"

On my test the attachments were not in a useful format. If your logfiles are in unix format and you want to read them with something like Windows Notepad it is necessary to convert the files with "ux2dos" (or "unix2dos") in the pipeline to "uuencode".

1 Like

hi dahu, methyl, thanks a lot. and all it needed was that magic word! :b: