Search code examples
bashshellemailmailx

Monitoring a file and wanting to send an email with the `mail` command


I am going to monitor a file with a [ -s filename ] option and when that file gets data, to email me with appropriate information. I've searched the site and came up with a few options, but didn't click for me.

I'm trying to do the following to simply test "mail" I've also tried mailx. The user did not receive the email and the output provided is exactly the same for mail and mailx.

Ultimately, I'm going to edit the original bash script with the mail or mailx command, assuming I can get it to work.

This is what I'm doing and output command line returns when I hit, enter.

Thank you for any input for this, I totally appreciate it.


[user@somehost ~]$ echo "TEST" | mail -s subject user@mail.com

[user@somehost ~]$ send-mail: warning: inet_protocols: IPv6 support is disabled: Address family not supported by protocol
send-mail: warning: inet_protocols: configuring for IPv4 support only
postdrop: warning: inet_protocols: IPv6 support is disabled: Address family not supported by protocol
postdrop: warning: inet_protocols: configuring for IPv4 support only

Solution

  • Better to use inotifywait for the event you're after (perhaps CLOSE_WRITE?).

    You'll need to configure your mailer with an SMTP server, and possibly (hopefully) some credentials.

    I usually use the mailx from the heirloom-mailx package, with the following script:

    #!/bin/false
    
    function send_email {
      # args are: subject [to] [from_name] [from_address]
      #   subject is required
      #   to and from_* are optional, defaults below
    
      # stdin takes the message body... don't forget
    
      # this function uses mailx from heirloom-mailx
    
      local SMTP_SRVR="${YOUR_SERVER}"
      local SMTP_USER="${YOUR_USERNAME}"
      local SMTP_PASS="${YOUR_PASSWORD}"
    
      local DEFAULT_TO="${YOUR_RECIPIENT}"
      local DEFAULT_FROM_NAME="${YOUR_SENDER_NAME}"
      local DEFAULT_FROM_ADDR="${YOUR_SENDER_EMAIL}"
    
      if [ $# -lt 1 ]; then
        echo "${FUNCNAME}(): missing subject (arg 1)..." >&2
        return 1
      fi
      local SUBJECT="$1"
      shift
    
      if [ $# -lt 1 ]; then
        local TO="${DEFAULT_TO}"
      else
        local TO="$1"
        shift
      fi
    
      if [ $# -lt 1 ]; then
        local FROM="${DEFAULT_FROM_NAME}"
      else
        local FROM="$1"
        shift
      fi
    
      if [ $# -lt 1 ]; then
        FROM="${FROM} <${DEFAULT_FROM_ADDR}>"
      else
        FROM="${FROM} <$1>"
        shift
      fi
    
      mailx -s"${SUBJECT}" -r"${FROM}" -Ssmtp="${SMTP_SRVR}" -Ssmtp-auth-user="${SMTP_USER}" -Ssmtp-auth-password="${SMTP_PASS}" "${TO}"
      return $?
    }
    

    You can then use the above (e.g: my_send_email.inc) from another script like this:

    #!/bin/bash
    
    source my_send_email.inc
    
    echo "Testing" | send_email "${MY_EMAIL}"