Skip to content
Advertisement

Crontab not able to call mailx used via python subPrrocess

I have a python file (say, mail_it.py) in which I have written a function to send the mails. Code is as below:-

def send_mail(recipient, subject, file_to_mail, body):
try:
    process = subprocess.Popen(['mailx', '-s', subject,'-a',file_to_mail, recipient], stdin=subprocess.PIPE)
except Exception as error:
  print(error)
process.communicate(body)

send_mail('abc@example.com', 'subject', 'file_name', 'body')

When I run this python file directly via unix command:

python3 mail_it.py

It sends the mail. But when I set this file to run via crontab. I get the following error:

[Errno 2] No such file or directory: 'mailx': 'mailx'

Thanks in advance!

Advertisement

Answer

this is a problem with the your processes environment , more specifically the it’s $PATH.

If you running it from your shell it will be on your $PATH.

find out where your mailx program is with

which mailx

and the try editing your code with is absolute path like (this is just an example your system will be different).

process = subprocess.Popen(['/usr/local/mailx', .......................

depending what other environment setting mailx needs, and it unix permissions, then you may have to edit your crontab settings.

Also pay attention what user the crontab is running your process as. Is it what your expect?

Advertisement