[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [msmtp-users] From Header for Cron Jobs



On Wed, Jul 05, 2017 at 04:13:38PM -0400, ryan wrote:
> I have recently switched from SSMTP to MSMTP because of problem with SSMTP and lack of support for it.  Since switching to MSMTP any emails generated as a result of a cron job show as from just "root" instead of {user}@{fqdn}.domain.com.
> 
> I have done some troubleshooting and it looks like MSMTP is properly setting the MAIL FROM: in the SMTP connection, however there is a "From" header that says "root (Cron Deamon)" which is possibly not getting changed properly 
> 
> If anyone has a suggestion on how to remedy this that would be great.  If not perhaps a feature request to fix the headers as well as the SMTP MAIL FROM
> 
> thanks

My solution for this is:
cp -a /usr/sbin/sendmail /usr/sbin/sendmail.real
cat <<END >/usr/sbin/sendmail
#!/bin/bash

LogOutput='y'
EmailOutput='y'
MailFrom='hostname-cron@...45...'
# Multiple addresses may be separated by commas
MailTo='hostname-cron@...45...'
# If 'n', $MailTo is prepended to the cron MAILTO
ReplaceMailTo='n'
# If 'y', unqualified addresses are removed from the cron MAILTO before appending
DropUnqualifiedTo='y'



# Copy arguments to an array
Args=("$@")

# Determine whether we were called by cron
Cron='n'
for ArgNum in "${!Args[@]}" ; do
  if [ "${Args[$ArgNum]}" = '-FCronDaemon' ] ; then
    Cron='y'
    break
  fi
done

# If we were not called by cron, simply pass through to the real sendmail
if [ "$Cron" = 'n' ] ; then
  /usr/sbin/sendmail.real "$@"
  exit $?
fi

# If we get here, we were called by cron
Status=0

# Read STDIN into an environment variable so we can both log and email it
Input="$(cat)"

# Log the cron job's output (everything after the message headers)
if [ "$LogOutput" = 'y' ] ; then
  echo "$Input" | perl -0777 -n -e '@i=split(/\n\n/, $_, 2); print($i[1]);' | logger -p cron.warn --skip-empty
  Status=$?
fi

if [ "$EmailOutput" = 'y' ] ; then
  # Replace the From addresses
  if [ -n "$MailFrom" ] ; then
    Args[$ArgNum]="-F$MailFrom"
    Input="$(echo "$Input" | perl -0777 -p -e "\$f='$MailFrom';" -e 's/^From: root .*$/From: $f/m')"
  fi

  # Modify the To addresses
  if [ -n "$MailTo" ] ; then
    if [ "$ReplaceMailTo" = 'n' ] ; then
      CronMailTo="${Args[-1]}"
      if [ "$DropUnqualifiedTo" = 'y' ] ; then
        CronMailTo="$(echo "$CronMailTo" | perl -n -e 'print join(",", grep(/@/, split(/,/)));')"
      fi
      [ -n "$CronMailTo" ] && MailTo="$MailTo,$CronMailTo"
    fi
    Args[-1]="$MailTo"
    Input="$(echo "$Input" | perl -0777 -p -e "\$t='$MailTo';" -e 's/^To: .*$/To: $t/m')"
  fi

  # Send the email
  echo "$Input" | /usr/sbin/sendmail.real "${Args[@]}"
  Status=$?
fi

exit $Status
END