0

I have a php script that is going to be a cron job and it was working fine until I added the email script I have been using.

I have used the email script all over the site before but when I try and run the cron job using it from the command line it fails.

The mail script looks as followed

    <?php

require_once "Mail.php";

function sendMail($to, $from, $subject, $message) {

        $no_errors = true;

        $host = "ssl://smtp.server.com";
        $port = "465";
        $username1 = "username";
        $password = "password";

        $headers = array ('From' => 'myfromemail@myemail.com',
          'To' => $to,
          'Subject' => $subject);
        $smtp = Mail::factory('smtp',
          array ('host' => $host,
            'port' => $port,
            'auth' => true,
            'username' => $username1,
            'password' => $password));

        $mail = $smtp->send($to, $headers, $message);

        if (PEAR::isError($mail)) {

            $no_errors = false;

            echo $mail->getMessage();

        } else {

            $no_errors = true;

         }

        return $no_errors;

        }

?>

If I comment out the include send_mail.php it works fine but doesn't send email.

Any ideas?

Dfranc3373
  • 2,048
  • 4
  • 30
  • 44

4 Answers4

1

You will need to make sure that, when the script is ran from cron, it has the proper working folder set, so it can load mail.php. Using the getcwd() and chdir() functions are the two you need to use.

Usually, when ran from web browser (on an Apache server), the working directory is /var/www, but from cron, it is usually the root of the filesystem, /.

Whisperity
  • 3,012
  • 1
  • 19
  • 36
1

When including external files, you need to be conscious of where the file is, and then where PHP will look for it. You can inspect where it will look with get_include_path() and set it with set_include_path(). When you set a new one, you want to ADD (not replace) the directory where Mail.php is installed. Use get_include_path() . PATH_SEPARATOR . $yourPath as the new value.

Chris Trahey
  • 18,202
  • 1
  • 42
  • 55
1

The standard folder when you're running a cron is probably different to the folder in which this include is contained. Try this:

require_once realpath( dirname( __FILE__ ) . '/Mail.php' );

In the general case, you can add in .. or folder structures as required - and it should still work.

halfer
  • 19,824
  • 17
  • 99
  • 186
0

Try "locate Mail.php" from Command line, and then try full path of this script in your require_once

Also try to dump the response into a log file, when it's ran via cron:

Cron Job Log - How to Log?

Community
  • 1
  • 1
Doug Molineux
  • 12,283
  • 25
  • 92
  • 144