Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * MailSender
- * Per utilitzar PHPMailer de forma molt més senzilla i
- * utilitzant plantilles HTML.
- *
- * Dependencies:
- * - PHPMailer
- *
- * @version 0.24
- * @license MIT
- * @author Mario M. <gameofender@gmail.com>
- */
- class MailSender {
- var $mailer;
- var $template;
- var $body = '';
- var $body_alt = '';
- public function __construct($host, $username, $password, $isHTML = true) {
- $mail = new PHPMailer;
- $mail->isSMTP(); // Set mailer to use SMTP
- $mail->Host = $host; // Specify main and backup SMTP servers
- $mail->SMTPAuth = true; // Enable SMTP authentication
- $mail->Username = $username; // SMTP username
- $mail->Password = $password; // SMTP password
- $mail->isHTML($isHTML); // Set email format to HTML
- $mail->CharSet = 'UTF-8';
- // Save PHPMailer Instance
- $this->mailer = $mail;
- }
- /**
- * Template .html path
- * @param String $path
- */
- public function setTemplateURL($path) {
- $this->template = $path;
- $this->body = file_get_contents($this->template);
- }
- public function setBodyAlt($string) {
- $this->body_alt = $string;
- }
- /**
- * Remplace mail variables inside template with {{var}} notation.
- * @return Array
- */
- public function compose($args) {
- if(is_array($args)) {
- foreach($args as $key => $value){
- if(!is_array($value)) $this->body = preg_replace('/{{'.$key.'}}/', $value, $this->body);
- }
- }
- }
- /**
- * Send!
- * @param [type] $from [description]
- * @param [type] $to [description]
- * @param [type] $subject [description]
- * @return [type] [description]
- */
- function send($from, $to, $subject) {
- $this->mailer->Subject = $subject;
- $this->mailer->Body = $this->body;
- if(!empty($this->body_alt)) $this->mailer->AltBody = $this->body_alt;
- if(is_array($from)) $this->mailer->setFrom($from[0], $from[1]);
- else $this->mailer->setFrom($from);
- if(!is_array($to)) $this->mailer->addAddress($to);
- else {
- foreach ($to as $email => $name) {
- $this->mailer->addBcc($email, $name);
- }
- }
- return $this->mailer->send();
- }
- }
- ?>
- <?php
- //////////////////////////////////////////////////////////////////////////////////////
- // How to use:
- $mailer = new MailSender('localhost', 'smtp_user', 'smtp_password');
- // Set .html template
- $mailer->setTemplateURL('views/mails/message.html');
- // Remplace strings patterns {{var}} on HTML template
- // ex.: `<h2>{{name}}</h2>` ===> `<h2>Mario M.</h2>`
- $mailer->compose(array(
- name => 'Mario M.',
- sex => 'Mr.',
- email => 'gameofender@gmail.com'
- ));
- // Send email with from, to and Subject.
- $sended = $mailer->send(
- array('from@email.com', 'From name'),
- 'to@email.com',
- 'subject'
- );
- /////////////////////////////////////////////////////////////////////////////////////////
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement