Posted 2004-11-18T15:37:00+01:00 in php

Email attachments from the command line

My hosting provider provides shell access and a crontab. I use that to email a database dump once a week. There's a PHP script to do that for me


        
<?php

    
# send-att.php
    # Send a file from standard input to the given address.
    #
    #
    # Example:
    # $ cat ~/.bashrc | gzip | \
    #      ./send-gz.php "Bash settings" \
    #      "bashrc.gz" "application/x-gzip" "jeroenpXredslider.net"

    
$subject = $argv[1];
    
$filename = $argv[2];
    
$contenttype = $argv[3];
    
$to = $argv[4];
    
$time = time();
    
$timestamp = strftime("%D %T", $time);
    
$hostname = gethostbyaddr("127.0.0.1");
    
$message = "(This attachment was generated $timestamp
using send-att.php on '$hostname'.)"
;
   
    
$data = @file_get_contents("php://stdin") or die("Couldn't open stdin.");
    
$attachment = chunk_split(base64_encode($data));
    
$sep = md5(uniqid($time));

    
$fields = array(
        
"MIME-Version: 1.0",
        
"Content-Type: multipart/mixed; boundary=\"$sep\"",
        
"--$sep",
        
"Content-Type: text/plain; charset=ISO-8859-1",
        
"",
        
$message,
        
"--$sep",
        
"Content-Type: $contenttype",
        
"Content-Transfer-Encoding: base64",
        
"Content-Disposition: attachment; filename=\"$filename\"",
        
"",
        
$attachment);
    
    
mail($to, $subject, "", join($fields, "\r\n"));
    exit(
0);
?>

In combination with the dump script below, a simple shell script does all the action:

$ php select-star.php | gzip | php send-att.php \
    "Bookreviews dump" \
    "bookreview.dmp.gz" \
    "application/x-gzip" \
    "Jeroen Pulles <user@domain.net>"