0

I'm hoping someone could help me out here. I've searched everywhere and asked a friend, but can't find anything. I have a python script that reads a couple files, fixes some barcode numbers and then emails, using smtplib, the 2 files as attachments. The script runs good from the command line, both attachments are sent with the email. But, from Cron the email is sent, but the attachments are not. Does anyone know if there is a config that needs to be changed or if there should be something else in the python script to allow for Cron to send the attachments?

Here is my line in crontab, nothing fancy

15 01 * * * /home/user/folder/./script.py

I'm using cron to send other emails from python scripts and haven't had any problems. Only difference is that none of the others have attachments.

If someone has heard of this and can help out, that would be great! If you need part or all of the python code, please let me know.

Thanks

  • Most likely the handling of the attachments relies on an environment setting that's not the same in the cron environment (most trivially for example if it's looking for the attachments in path that's relative to PWD) – steeldriver Jan 17 '18 at 1:35
  • You were right, cron was running the script but could not find the attachment in that directory. I had to write a shell script to cd to that directory. Thanks for the help! – Tim Jan 18 '18 at 13:39
0

In case someone else has this problem, here's how I solved it, there's probably a lot of other ways and if someone has a better one, please let me know.

Cron was not running the script in the correct environment, so it could run the script but it was looking in the wrong directory for the attachments. It couldn't find them. What I did was write a shell script like this:

#!/bin/bash
cd /path/to/directory
python file.py

This allows the environment to change to the directory that I want to work in. Now that attachments are found since the script and the attachments are in the same directory.

I changed the Cron job to run the shell script:

30 01 * * * /path/to/script/./script.sh

I'm not sure if this is just a work around or an actual solution, but it works and that good for me!

  • This is rather a workaround. But never mind. You should probably search the attachements in (or relative to) the path where the Python script is located: import os; script_dir=os.path.dirname(os.path.realpath(__file__)) Now you can find the attachements relative to script_dir and drop your shell wrapper. /// You could also change your cronjob to 30 01 * * * cd /path/to/script; python file.py (and again drop the shell wrapper). – PerlDuck Jan 18 '18 at 14:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.