Skip to content

Instantly share code, notes, and snippets.

@mpratt
Last active December 31, 2015 04:39
Show Gist options
  • Save mpratt/7935754 to your computer and use it in GitHub Desktop.
Save mpratt/7935754 to your computer and use it in GitHub Desktop.
A simple Mailer class
<?php
/**
* Mailer.php
*
* @author Michael Pratt <[email protected]>
* @link http://www.michael-pratt.com/
* @license MIT
*/
namespace Mailer;
/**
* A very simple mailer class that uses php's default mail function.
*
* Usage:
* $mailer = new Mailer('[email protected]', '[email protected]', 'subject', 'body');
* try {
* $mailer->send();
* } catch(\Exception $e) {}
*/
class Mailer
{
/** @var string The email where the email is going to be sent **/
protected $to;
/** @var string The email from where is going to be sent **/
protected $from;
/** @var string The subject of the email **/
protected $subject;
/** @var string The body of the email **/
protected $body;
/** @var array Headers of the email **/
protected $headers = array();
/**
* Construct
*
* @param string $from
* @param string $to
* @param string $subject
* @param string $body
* @param bool $html Send the content as html or as plain text.
* @return void
*/
public function __construct($from, $to, $subject, $body, $html = true)
{
$this->from = $from;
$this->addMailHeader('From', $this->from);
$this->addMailHeader('Reply-To', $this->from);
$this->addMailHeader('Return-Path', $this->from);
$this->addMailHeader('X-mailer', 'PHP/SimpleMailer');
$this->addMailHeader('MIME-Version', '1.0');
// $this->addMailHeader('Content-Transfer-Encoding', '8bit');
if ($html) {
$this->addMailHeader('Content-type', 'text/html; charset=UTF-8');
} else {
$this->addMailHeader('Content-type', 'text/plain; charset=UTF-8');
}
$this->to = $to;
$this->subject = $subject;
$this->body = $body;
}
/**
* Appends stuff to the mail header
*
* @param string $header The name of the header
* @param string $value The content of the header
* @return void
*/
public function addMailHeader($header, $value)
{
$this->headers[$header] = $value;
}
/**
* Sends the mail.
*
* @return bool
*
* @throws InvalidArgumentException when an invalid Email Address is given
* @throws RuntimeException if the operation was not successful.
*
* @codeCoverageIgnore
*/
public function send()
{
if (!filter_var($this->from, FILTER_VALIDATE_EMAIL)) {
throw new \InvalidArgumentException('The address ' . $this->from . ' does not appear to be valid!');
} elseif (!filter_var($this->to, FILTER_VALIDATE_EMAIL)) {
throw new \InvalidArgumentException('The address ' . $this->to . ' does not appear to be valid!');
}
$headers = '';
foreach ($this->headers as $key => $value) {
$headers .= $key . ": " . $value . "\r\n";
}
if (!mail($this->to, '=?utf-8?B?' . base64_encode($this->subject) . '?=', $this->body, $headers)) {
throw new \RuntimeException('Error sending mail');
}
return true;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment