Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 10 of 10
  1. #1
    Regular Coder
    Join Date
    Sep 2007
    Posts
    809
    Thanks
    5
    Thanked 2 Times in 2 Posts

    Sending an attachment via mail()

    Hi all,

    I currently have some code which when the page is loaded up prompts the user to save a CSV file:

    PHP Code:
    <?php
        
    // THIS EXPORTS ONE TABLE AT A TIME
        
    $host 'localhost';
        
    $user 'my_user';
        
    $pass 'my_pass';
        
    $db 'my_database';
        
    $table 'my_tbl';
        
    $file 'jobseekers_export';

        
    $link mysql_connect($host$user$pass) or die("Can not connect." mysql_error());
        
    mysql_select_db($db) or die("Can not connect.");

        
    $result mysql_query("SHOW COLUMNS FROM ".$table."");
        
    $i 0;
            if (
    mysql_num_rows($result) > 0) {
                while (
    $row mysql_fetch_assoc($result)) {
        
    $csv_output .= $row['Field'].", ";
        
    $i++;
    }
    }
        
    $csv_output .= "\n";

        
    $values mysql_query("SELECT * FROM ".$table."");
            while (
    $rowr mysql_fetch_row($values)) {
                for (
    $j=0;$j<$i;$j++) {
        
    $csv_output .= $rowr[$j].", ";
    }
        
    $csv_output .= "\n";
    }

        
    $filename $file."_".date("Y-m-d_H-i",time());
        
    header("Content-type: application/vnd.ms-excel");
        
    header("Content-disposition: csv" date("Y-m-d") . ".csv");
        
    header"Content-disposition: filename=".$filename.".csv");
        print 
    $csv_output;
        exit;
    ?>
    What I would like to do, is have this file emailed rather than having to actually visit a URL to save it. I know the basics of the mail() function, but I have no idea how I would use it to get this file to send as an attachment.

    I have setup a Cron job on the server, which deals with the issue of automatically sending the email, if only I could get the file to be an attachment all would be well.

    I have Googled this, but found no good tutorials, at least never find one I could make any sense of.

    Would anyone be willing to advise?

    Many Thanks,

    Greens85

  • #2
    UE Antagonizer Fumigator's Avatar
    Join Date
    Dec 2005
    Location
    Utah, USA, Northwestern hemisphere, Earth, Solar System, Milky Way Galaxy, Alpha Quadrant
    Posts
    7,691
    Thanks
    42
    Thanked 637 Times in 625 Posts
    I would really recommend PHPMailer, a free 3rd party mail extension which makes sending email with attachments a trivial matter.

    http://phpmailer.worxware.com/

  • #3
    Regular Coder
    Join Date
    Sep 2007
    Posts
    809
    Thanks
    5
    Thanked 2 Times in 2 Posts
    Quote Originally Posted by Fumigator View Post
    I would really recommend PHPMailer, a free 3rd party mail extension which makes sending email with attachments a trivial matter.

    http://phpmailer.worxware.com/
    Hey Fumigator,

    I think I've used this before the problem is kinda more that I'm not sure how to include the file if that makes sense. I'm not sure that the file is saving to the server, so how do I include it in the code...

    As I got the script from another site, im not sure which variable the file sits in... i.e. is it $filename or $file or $csv_output etc?

  • #4
    UE Antagonizer Fumigator's Avatar
    Join Date
    Dec 2005
    Location
    Utah, USA, Northwestern hemisphere, Earth, Solar System, Milky Way Galaxy, Alpha Quadrant
    Posts
    7,691
    Thanks
    42
    Thanked 637 Times in 625 Posts
    Quote Originally Posted by greens85 View Post
    Hey Fumigator,

    I think I've used this before the problem is kinda more that I'm not sure how to include the file if that makes sense. I'm not sure that the file is saving to the server, so how do I include it in the code...

    As I got the script from another site, im not sure which variable the file sits in... i.e. is it $filename or $file or $csv_output etc?
    The script you posted doesn't save anything to your web server; it collects data into a variable and then prompts the user to save this variable (as a file) to their computer (the client computer).

    Use PHPMailer and modify this process to attach the variable (as a file) to an email, then send the email out.

  • #5
    Regular Coder
    Join Date
    Sep 2007
    Posts
    809
    Thanks
    5
    Thanked 2 Times in 2 Posts
    Quote Originally Posted by Fumigator View Post
    The script you posted doesn't save anything to your web server; it collects data into a variable and then prompts the user to save this variable (as a file) to their computer (the client computer).

    Use PHPMailer and modify this process to attach the variable (as a file) to an email, then send the email out.
    Hi,

    I have now downloaded PHP mailer and installed it to the server as per the instructions on the site...

    Following the example on their website - http://phpmailer.worxware.com/index.php?pg=examplebmail

    I have tried to incorporate it into my code, in order to add an attachment. However it just seems to be ignoring the code:

    PHP Code:
    <?php
        
    require_once('PHP_Mailer/class.phpmailer.php');

        
    $mail = new PHPMailer(); // defaults to using php "mail()"
        
    $body file_get_contents('contents.html');
        
    $body eregi_replace("[\]",'',$body);
        
    $mail->AddReplyTo("noreply@educationvacancies.com","No Reply");
        
    $mail->SetFrom('autobackup@educationvacancies.com''Auto Backup'); 
        
    $mail->AddReplyTo("noreply@educationvacancies.com","No Reply");
        
    $address "dgreenwell@educationvacancies.com";
        
    $mail->AddAddress($address"David Greenwell");
        
    $mail->Subject "SQL Backup";
        
    $mail->AltBody "To view the message, please use an HTML compatible email viewer!"// optional, comment out and test
        
    $mail->MsgHTML($body);
        
    $mail->AddAttachment("images/phpmailer.gif");      // attachment
        
    $mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
         
        
    $mail->AddAttachment("filename=".$filename.".csv"); // TRIED TO ADD THE FILE HERE WITH THIS LINE
        
        
    if(!$mail->Send()) {
            echo 
    "Mailer Error: " $mail->ErrorInfo;
        } else {
            echo 
    "Message sent!";
        }
    ?>
    I don't receive an email from autobackup@educationvacancies.com, the only email I recieve is confirmation from the cron job 'Cron Daemon', this email contains the data that has been pulled from the table as the body text...

    If I comment out the following lines:

    PHP Code:
    <?php
    $filename 
    $file."_".date("Y-m-d_H-i",time());
        
    header("Content-type: application/vnd.ms-excel");
        
    header("Content-disposition: csv" date("Y-m-d") . ".csv");
        
    header"Content-disposition: filename=".$filename.".csv");
        print 
    $csv_output;
    ?>
    I don't even recieve an email from the 'Cron Daemon'... any thoughts?

    Many thanks

  • #6
    UE Antagonizer Fumigator's Avatar
    Join Date
    Dec 2005
    Location
    Utah, USA, Northwestern hemisphere, Earth, Solar System, Milky Way Galaxy, Alpha Quadrant
    Posts
    7,691
    Thanks
    42
    Thanked 637 Times in 625 Posts
    PHP Code:
        if(!$mail->Send()) {
            echo 
    "Mailer Error: " $mail->ErrorInfo;
        } else {
            echo 
    "Message sent!";
        } 
    Which of those two echo statements do you see?

  • #7
    Regular Coder
    Join Date
    Sep 2007
    Posts
    809
    Thanks
    5
    Thanked 2 Times in 2 Posts
    Quote Originally Posted by Fumigator View Post
    PHP Code:
        if(!$mail->Send()) {
            echo 
    "Mailer Error: " $mail->ErrorInfo;
        } else {
            echo 
    "Message sent!";
        } 
    Which of those two echo statements do you see?
    If I go to the page I am prompted for the download without seeing either of those

  • #8
    UE Antagonizer Fumigator's Avatar
    Join Date
    Dec 2005
    Location
    Utah, USA, Northwestern hemisphere, Earth, Solar System, Milky Way Galaxy, Alpha Quadrant
    Posts
    7,691
    Thanks
    42
    Thanked 637 Times in 625 Posts
    So that code isn't even running.

  • #9
    Regular Coder
    Join Date
    Sep 2007
    Posts
    809
    Thanks
    5
    Thanked 2 Times in 2 Posts
    Quote Originally Posted by Fumigator View Post
    So that code isn't even running.
    After i commented these lines out:

    PHP Code:
    //header("Content-type: application/vnd.ms-excel");
    //header("Content-disposition: csv" . date("Y-m-d") . ".csv");
    //header("Content-disposition: filename=".$filename.".csv");
    //print $csv_output; 
    I received the message:

    Could not access file: filename=jobseekers_export_2010-02-10_11-13.csv Message sent!

    I also recieved an email containing the body message I had set but the email didn't contain any attachment!


  • #10
    Regular Coder
    Join Date
    Sep 2007
    Posts
    809
    Thanks
    5
    Thanked 2 Times in 2 Posts
    Got it working like so:

    PHP Code:
    <?php
        
    // THIS EXPORTS ONE TABLE AT A TIME
        
    $host 'host';
        
    $user 'user';
        
    $pass 'pass';
        
    $db 'db';
        
    $table 'table';

        
    $link mysql_connect($host$user$pass) or die("Can not connect." mysql_error());
        
    mysql_select_db($db) or die("Can not connect.");

        
    $result mysql_query("SHOW COLUMNS FROM ".$table."");
        
    $i 0;
            if (
    mysql_num_rows($result) > 0) {
                while (
    $row mysql_fetch_assoc($result)) {
        
    $csv_output .= $row['Field'].", ";
        
    $i++;
        }
        }
        
    $csv_output .= "\n";

        
    $values mysql_query("SELECT * FROM ".$table."");
            while (
    $rowr mysql_fetch_row($values)) {
                for (
    $j=0;$j<$i;$j++) {
        
    $csv_output .= '"'.$rowr[$j].'",'
        }
        
    $csv_output .= "\n";
        }
        
        
    $csv_filename "subcities.csv";
        
    $open fopen($csv_filename"w");
        
    fwrite ($open"$csv_output");
        
    fclose ($open);
        
        require_once(
    '../class.phpmailer.php');

        
    $mail = new PHPMailer(); // defaults to using php "mail()"
        //$body = file_get_contents('contents.html');
        
    $body "Please find attached the daily SQL backup!";
        
    $body eregi_replace("[\]",'',$body);
        
    $mail->AddReplyTo("noreply@educationvacancies.com","No Reply");
        
    $mail->SetFrom('autobackup@educationvacancies.com''Auto Backup'); 
        
    $mail->AddReplyTo("noreply@educationvacancies.com","No Reply");
        
    $address "dgreenwell@educationvacancies.com";
        
    $mail->AddAddress($address"David Greenwell");
        
    $mail->Subject "SQL Backup";
        
    $mail->AltBody "To view the message, please use an HTML compatible email viewer!"// optional, comment out and test
        
    $mail->MsgHTML($body);
         
        
    $mail->AddAttachment("subcities.csv");
        
        if(!
    $mail->Send()) {
            echo 
    "Mailer Error: " $mail->ErrorInfo;
        } else {
            echo 
    "Message sent!";
        }
    ?>
    I've then got a script & cron like this for each one of my tables, I know it's a bit clunky but it works which is a good starting point.
    Last edited by greens85; 02-10-2010 at 03:04 PM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •