Thursday, July 5, 2012

[Bash] mail2me: send email with attachments from terminal

This is mutt version. A "mail" version is here.
#!/bin/bash
# send files to an email account as the attachment(s)
# usage:
#           mail2me email -s 'YourSubject'  YourAttachments
#           http://scriptdemo.blogspot.com

function isEmail()
{
   cEmail=`echo $1 | grep "^[a-zA-Z]\+\([._][a-zA-Z0-9]\+\)*@\([a-zA-Z0-9]\+\.\)\+[a-zA-Z]\{2,3\}$"`
   if [ ${#cEmail} -gt 0 ]; then
      echo "true"
   else
      echo "false"
   fi
}
function isServerOn()
{
  myS=$1
  myp=`ping -c 2 ${myS} 2>&1 | grep "% packet" | awk '{print $6*100}'`
  if [ ${#myp} -eq 0 ]; then
     echo "-1" #server: ${myS} is not valid
  elif [ ${myp} -eq 100 ]; then
     echo "0" #server: ${myS} is off
  else
     echo "1" #server: ${myS} is $(( 100 - ${myp}))% response
  fi
}

if [ $# -le 1 ]; then
   echo "usage: mail2me email -s Subject file1 [file2] ..."
   exit
fi

#check email
targetEmail=$1
isValidEmail=`isEmail ${targetEmail}`
[ ${isValidEmail} == "false" ] && echo "${targetEmail} is not a valid email address!!!" && exit

#check smtp server
smtpS=`echo ${targetEmail} | awk -F\@ '{print $2}'`
smtpS="smtp.${smtpS}"
isOnline=`isServerOn ${smtpS}`
if [ ${isOnline} == "-1" ]; then
     echo "SMTP server: ${smtpS} is invalid. STOP" && exit
elif [ ${isOnline} == "0" ]; then
     echo "SMTP server: ${smtpS} is offline. STOP" && exit
fi

#send email
numF=0
nf=2
isDebug=0
shift #shift the email
while [ $# -ge 1 ]
do
    case $1 in
       -s|-S)
         mysubj=$2
         shift; shift;
         ;;
       -d|-D)
         isDebug=1
         shift
         ;;
       *)
         if [ -f ${tmpfn} ]; then
            myfile[${numF}]=$1
            numF=`expr ${numF} + 1`
         else
            echo "$1 is not found!"
         fi
         shift
         ;;
     esac
done

if [ ${numF} -eq 1 ]; then
   [ ${#mysubj} -eq 0 ] && mysubj="[script] ${myfile[0]}"
elif [ ${numF} -gt 1 ]; then
   [ ${#mysubj} -eq 0 ] && mysubj="[script] backup ${myfile[0]} etc."
else
   echo "no file is found!!!" && exit
fi

if [ ${isDebug} -eq 1 ]; then
   echo "echo \"The attachment is ${myfile[*]} sent by `whoami` from `hostname`\" | mutt -s '${mysubj}' -a ${myfile[*]} -- ${targetEmail}"
else
   echo "The attachment is ${myfile[*]} sent by `whoami` from `hostname` " | mutt -s "${mysubj}" -a ${myfile[*]} -- ${targetEmail}
fi

No comments:

ShowCalendar