UPDATE: Added application of the basename() function to the attached filenames to get the filenames only.
This php class lets you attach multiple files and send emails via Postfix without digging into the messy headers 😀
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
<?php class Mailer { function __construct($to="",$from="",$sub="",$msg="",$files=array()) { $this->to = $to; $this->from = $from; $this->sub = $sub; $this->msg = $msg; $this->files = $files; } function attachFile($file) { if(!empty($file)) { $this->files[] = $file; } } function setMessage($msg) { if(!empty($msg)) { $this->msg = $msg; } } function setTo($to) { if(!empty($to)) { $this->to = $to; } } function setFrom($from) { if(!empty($from)) { $this->from = $from; } } function setSubject($sub) { if(!empty($sub)) { $this->sub = $sub; } } function sendMail() { $files = $this->files; // email fields: to, from, subject, and so on $to = $this->to; $from = $this->from; $subject = $this->sub; $message = $this->msg; $headers = "From: $from "; // boundary $semi_rand = md5(time()); $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; // headers for attachment $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; // multipart boundary $message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n"; $message .= "--{$mime_boundary}\n"; // preparing attachments for($x=0;$x<count($files);$x++) { $file = fopen($files[$x],"rb"); $data = fread($file,filesize($files[$x])); fclose($file); $data = chunk_split(base64_encode($data)); $message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" . "Content-Disposition: attachment;\n" . " filename=\"".basename($files[$x])."\"\n" . "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n"; $message .= "--{$mime_boundary}\n"; } // send $ok = @mail($to, $subject, $message, $headers); return $ok; } } ?> |
Example USE:
1 2 3 4 5 6 7 8 9 10 11 |
<?php include("mailer.php"); $m = new Mailer(); $m->setTo("maSnun <masnun@gmail.com>"); $m->setFrom("phpGeek <masnun@leevio.com>"); $m->setSubject("A bunch of files"); $m->setMessage("Hello buddy! Files attached!"); $m->attachFile("images/Screenshot.png"); if($m->sendMail()) { echo "Sent \n"; } else { echo "failed \n"; } ?> |
Happy Mailing! 😀
2 replies on “A PHP Mailer Class”
[…] Read more here: A PHP Mailer Class « maSnun.com […]
[…] post: A PHP Mailer Class « maSnun.com […]