PHP Class Mail

With this E-Mail Class you can send Plain Text, HTML and attach Files via Web-URL. Mixed E-Mail Text/HTML with/without Attachment are also possible.

<?php

/**
 * This script is part of the newsletter module.
 * Library for mailing.
 *
 * @author Christian Koch <c.koch@chriskoch.net>
 * @copyright Christian Koch <c.koch@chriskoch.net>
 */
class Mail {
	/**
	 * Mail recipient.
	 *
	 * @var string
	 */
	private $strMailRecipient = '';

	/**
	 * Mail sender.
	 *
	 * @var string
	 */
	private $strMailSender = '';

	/**
	 * Mail reply to.
	 *
	 * @var string
	 */
	private $strMailReplyTo = '';

	/**
	 * Mail subject.
	 *
	 * @var string
	 */
	private $strMailSubject = '';

	/**
	 * Mail palintext message.
	 *
	 * @var string
	 */
	private $strMailPlainText = '';

	/**
	 * Mail HTML message.
	 *
	 * @var string
	 */
	private $strMailHTML = '';

	/**
	 * Array with attachment paths.
	 *
	 * @return array
	 */
	private $arrAttachment = array();

	/**
	 * Encoding type, by default UTF-8.
	 *
	 * @var string
	 */
	private $strEncoding = 'UTF-8';

	public function __construct() {}

	/**
	 * Set attachment path.
	 *
	 * @param string $strFile
	 * @param string $strName
	 * @param string $strMime
	 */
	public function setAttachment($strFile, $strName, $strMime) {
		$this->arrAttachment[] = array(
			'file' => $strFile,
			'name' => $strName,
			'mime' => $strMime
		);
	}

	/**
	 * Set encoding.
	 *
	 * @param string $str
	 */
	public function setEncoding($str) {
		$this->strEncoding = $str;
	}

	/**
	 * Set mail html message.
	 *
	 * @param string $str
	 */
	public function setMailHTML($str) {
		$this->strMailHTML = $str;
	}

	/**
	 * Set mail subject.
	 *
	 * @param string $str
	 */
	public function setMailPlainText($str) {
		$str = strip_tags($str);

		$this->strMailPlainText = $str;
	}

	/**
	 * Set mail subject.
	 *
	 * @param string $str
	 */
	public function setMailSubject($str) {
		$str = strip_tags($str);

		$this->strMailSubject = $str;
	}

	/**
	 * Set mail sender address.
	 *
	 * @param string $str
	 */
	public function setMailRecipient($str) {
		$this->strMailRecipient = $str;
	}

	/**
	 * Get mail sender address.
	 *
	 */
	public function getMailRecipient() {
		return $this->strMailRecipient;
	}

	/**
	 * Set mail sender address.
	 *
	 * @param string $str
	 */
	public function setMailSender($str) {
		$this->strMailSender = $str;
	}

	/**
	 * Get mail sender address.
	 *
	 */
	public function getMailSender() {
		return $this->strMailSender;
	}

	/**
	 * Set mail reply to address.
	 *
	 * @param string $str
	 */
	public function setMailReplyTo($str) {
		$this->strMailReplyTo = $str;
	}

	/**
	 * Get mail reply to address.
	 *
	 * @return string
	 */
	public function getMailReplyTo() {
		if (empty($this->strMailReplyTo)) {
			$this->strMailReplyTo = substr_replace(
				$this->strMailSender,
				'noreply',
				0,
				strpos($this->strMailSender, '@'));
		}

		return $this->strMailReplyTo;
	}

	/**
	 * Send email.
	 *
	 */
	public function send() {
		$strMessageSeperator = $this->getMailSeperator();

		$strMailHeader = $this->getStdMailHeader();
		$strMailHeader .= "MIME-Version: 1.0\n";
		$strMailHeader .= count($this->arrAttachment) > 0 ? "Content-Type: multipart/mixed; " : "Content-Type: multipart/alternative; ";
		$strMailHeader .= "boundary=\"{$strMessageSeperator}\"\n\n";

		if (!empty($this->strMailHTML) && !empty($this->strMailPlainText)) {
			$strAlternativeMessageSeperator = $this->getMailSeperator();

			$strMailMessage = "--{$strMessageSeperator}\n";
			$strMailMessage .= "Content-Type: multipart/alternative; boundary=\"$strAlternativeMessageSeperator\"\n\n";
			$strMailMessage .= "--$strAlternativeMessageSeperator\n";
			$strMailMessage .= $this->getPreparedMailPlainText();
			$strMailMessage .= "--$strAlternativeMessageSeperator\n";
			$strMailMessage .= $this->getPreparedMailHTML();
			$strMailMessage .= "--$strAlternativeMessageSeperator--\n";
		} else if (!empty($this->strMailPlainText)) {
			$strMailMessage = "--{$strMessageSeperator}\n";
			$strMailMessage = $this->getPreparedMailPlainText();
		} else if (!empty($this->strMailHTML)) {
			$strMailMessage = "--{$strMessageSeperator}\n";
			$strMailMessage .= $this->getPreparedMailHTML();
		}

		for ($i=0; $i<count($this->arrAttachment); $i++) {
			if (ini_get('allow_url_fopen') == '1') {
				$strFileContents = file_get_contents($this->arrAttachment[$i]['file']);
			} else {
				if (function_exists('curl_init')) {
					$ch = curl_init();
					curl_setopt($ch, CURLOPT_URL, $this->arrAttachment[$i]['file']);
					curl_setopt($ch, CURLOPT_HEADER, 0);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
					curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0');
					$strFileContents = curl_exec($ch);
					curl_close($ch);
				}
			}

			$strMailMessage .= "--{$strMessageSeperator}\n";
			$strMailMessage .= $this->getPreparedMailAttachment($this->arrAttachment[$i]['mime'], $strFileContents, $this->arrAttachment[$i]['name']);
		}

		$strMailMessage .= "\n--{$strMessageSeperator}--\n";

		mb_internal_encoding($this->strEncoding);
		mail($this->strMailRecipient,
			mb_encode_mimeheader($this->strMailSubject, $this->strEncoding, 'B'),
			$strMailMessage,
			$strMailHeader);
	}

	/**
	 * Get prepared plaintext including mail content type part.
	 *
	 * @return string
	 */
	private function getPreparedMailPlainText() {
		$strResult = "Content-Type: text/plain; charset=\"{$this->strEncoding}\"\n";
		$strResult .= "Content-Transfer-Encoding: 7bit\n\n";
		$strResult .= "{$this->strMailPlainText}\n";

		return $strResult;
	}

	/**
	 * Get prepared HTML code including mail content type part.
	 *
	 * @return string
	 */
	private function getPreparedMailHTML() {
		$strHTMLMessage = $this->getHTMLReplacedUmlauts();

		$strResult  = "Content-Type: text/html; charset=\"{$this->strEncoding}\"\n";
		$strResult .= "Content-Transfer-Encoding: 7bit\n\n";
		$strResult .= "{$strHTMLMessage}\n";

		return $strResult;
	}

	/**
	 * Get prepared Attachment code including mail content type part.
	 *
	 * @param string $mime
	 * @param string $strFile
	 * @param string $strName
	 * @return string
	 */
	private function getPreparedMailAttachment($strMime, $strFile, $strName) {
		$strResult  = "Content-Type: $strMime; name=\"$strName\"\n";
		$strResult .= "Content-Transfer-Encoding: base64\n";
		$strResult .= "Content-Disposition: attachment; filename=\"$strName\"\n\n";
		$strResult .= base64_encode($strFile)."\n";

		return $strResult;
	}

	/**
	 * Get HTML message part with replaced umlauts to html code.
	 *
	 * @return string
	 */
	private function getHTMLReplacedUmlauts() {
		$arrUmlauts = array('/ä/', '/ü/', '/ö/', '/Ä/', '/Ü/', '/Ö/', '/ß/', '/„/', '/“/');
		$arrReplace = array('&auml;', '&uuml;', '&ouml;', '&Auml;', '&Uuml;', '&Ouml;', '&szlig;', '&bdquo;', '&ldquo;');

		$strResult = preg_replace($arrUmlauts, $arrReplace, $this->strMailHTML);

		return $strResult;
	}

	/**
	 * Get dynamic mail separator.
	 *
	 * @return string
	 */
	private function getMailSeperator() {
		return 'PHP'.md5(uniqid(time()));
	}

	/**
	 * Get standard mail header.
	 *
	 * @return string
	 */
	private function getStdMailHeader() {
		$strPHPVersion = phpversion();

		$strResult = "To: {$this->strMailRecipient}\n";
		$strResult .= "From: {$this->strMailSender}\n";
		$strResult .= 'Return-Path: '.$this->getMailReplyTo()."\n";
		$strResult .= 'Reply-To: '.$this->getMailReplyTo()."\n";
		$strResult .= "X-Mailer: PHP/{$strPHPVersion}\n";

		return $strResult;
	}
}

?>

Usage of class Mail.

...
$mail = new Mail();
$mail->setMailHTML($html);
$mail->setMailPlainText($plainText);
$mail->setMailSubject($subject);
$mail->setMailRecipient($recipient);
$mail->setMailSender('no-reply@mydomain.com');
$mail->setMailReplyTo('reply@mydomain.com');
  • Digg
  • del.icio.us
  • Facebook
  • Technorati
  • Twitthis
  • FriendFeed

POST A COMMENT

  • You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>