Skip to content

Instantly share code, notes, and snippets.

@twslankard
Created May 24, 2011 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twslankard/989244 to your computer and use it in GitHub Desktop.
Save twslankard/989244 to your computer and use it in GitHub Desktop.
simple Mime/Multipart email class for sending attachments and a text or html body in the charset of your choosing
<?php
/*
* simple Mime/Multipart email class for sending attachments and a text or html body in the charset of your choosing
* 2011 tom slankard, earthmine inc
*/
class Mime {
private $boundary = null;
public $to = null;
public $from = null;
public $subject = null;
public $body = null;
public $type = "text/plain; charset=utf-8";
public $attachments = Array();
public $headers = Array();
public function __construct() {
$this->boundary = md5(uniqid(time()));
}
private function separator() {
return "--$this->boundary\r\n";
}
private function lastSeparator() {
return "--$this->boundary--";
}
private function textHeaders($type) {
return
"Content-type: $type\r\n"
."Content-Transfer-Encoding: 7bit\r\n\r\n";
}
private function attachmentHeaders($filename) {
return
"Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"
."Content-Transfer-Encoding: base64\r\n"
."Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
}
private function constructText($message, $type) {
$result = $this->separator();
$result .= $this->textHeaders($type);
$result .= "$message\r\n\r\n";
return $result;
}
private function constructAttachment($filename) {
$path = pathinfo($filename);
$content = chunk_split(base64_encode(file_get_contents($filename)));
$result = $this->separator();
$result .= $this->attachmentHeaders($path['basename']);
$result .= "$content\r\n\r\n";
return $result;
}
private function constructMultipartMessage() {
$result = "From: $this->from\r\n"
."MIME-Version: 1.0\r\n"
."Content-Type: multipart/mixed; boundary=\"$this->boundary\"\r\n";
foreach($this->headers as $header) {
$result .= "$header\r\n";
}
if($this->body != null) {
$result .= $this->constructText($this->body, $this->type);
}
foreach($this->attachments as $attachment) {
$result .= $this->constructAttachment($attachment);
}
$result .= $this->lastSeparator();
return $result;
}
public function send() {
$message = $this->constructMultipartMessage();
return mail($this->to, $this->subject, "", $message);
}
}
/*
usage:
$mime = new Mime();
$mime->subject = "Hello World";
$mime->to = "tom@example.com";
$mime->from = "jerry@example.com";
$mime->body = "See ya later.";
$mime->attachments[] = "foo.png"; // attach local file named foo.png
$mime->send();
*/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment