A simple PHP class for sending email with attachments

PHP, 2015-06-16 23:55:29 UTC

Mail delivery feature is very important in a web-based applications. Many of developers use the library on the application. Some of the famous library are Swiftmailer and PHPMailer. Using library is simple but I think more simple is create a function or a class. So, you know exactly what is going on.

 
Here is the class;
class ApiMail 
{
    
    public static function mail_attachment($filename, 
            $path, 
            $mailto, 
            $from_mail, 
            $from_name, 
            $replyto, 
            $subject, 
            $message) 
    {
        $file = $path.$filename;
        $file_size = filesize($file);
        $handle = fopen($file, "r");
        $content = fread($handle, $file_size);
        fclose($handle);
        $content = chunk_split(base64_encode($content));
        $uid = md5(uniqid(time()));
        $name = basename($file);
        
        $header = "From: ".$from_name." <".$from_mail.">\r\n";
        $header .= "Reply-To: ".$replyto."\r\n";
        $header .= "MIME-Version: 1.0\r\n";
        $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
        $header .= "This is a multi-part message in MIME format.\r\n";
        $header .= "--".$uid."\r\n";
        $header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
        $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
        $header .= $message."\r\n\r\n";
        $header .= "--".$uid."\r\n";
        $header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
        $header .= "Content-Transfer-Encoding: base64\r\n";
        $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
        $header .= $content."\r\n\r\n";
        $header .= "--".$uid."--";
        if (mail($mailto, $subject, "", $header)) {
            echo '{ "message" : "success" }';
        } 
        else {
            echo '{ "message" : "fail" }';
        }
    }
    
}
 

You can use above class-method like below;

$filename = "the_file.xls";
$path = "/home/codescr/sites/application_name/temp/";
$mailto = "mailto@email.com";
$from_mail = "noreply@your_application.com";
$from_name = "Your Name";
$reply_to = "";
$subject = "Mail with attachement";
$message = "Mail with attachement. \nPlease download the attachement";
        
ApiMail::mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $reply_to, $subject, $message);


Simple, right?

Share: