Skip to content Skip to sidebar Skip to footer

Python: File Attachment Not Working While Sending Email By Crontab

The following source code is working fine when running manually but with crontab job mail is successfully sending but files are not attached.How can I fix it? #!/usr/bin/python im

Solution 1:

I think this issue is related to the folder where the attachment are located.

Keep in mind that if you run your script from crontab your python execution will probably be in a different folder than the one you're executing it manually from.

Therefore I suggest two possible solutions:

  • Use absolute paths for your attachments
  • Move Python path into your script path as soon as the script starts

You can achieve the 2nd result with a similar snippet:

import os

abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)

If you want to troubleshoot and better understand what is going on you could simply run the current version of your script using crontab and save its current working directory in a file using something similar:

with open('somefile.txt', 'a') as the_file:
    the_file.write(os.getcwd())

Edit: The issue was solved using the 2nd option suggested: Move Python path into your script path as soon your script starts.

Post a Comment for "Python: File Attachment Not Working While Sending Email By Crontab"