Skip to content

Instantly share code, notes, and snippets.

@fzn0x
Last active March 18, 2021 15:16
Show Gist options
  • Save fzn0x/7b4bcd191e047b6fec0bd89c3a9d9a49 to your computer and use it in GitHub Desktop.
Save fzn0x/7b4bcd191e047b6fec0bd89c3a9d9a49 to your computer and use it in GitHub Desktop.
PHPMailer Helper with shorter config.
<?php
//=============================================================================
// PHPMailerSender.php
//=============================================================================
//=============================================================================
/**
* MIT License.
*
* Author : Muhammad Fauzan
* Free To Distribute, Free To Explore, Free To Make Changes.
*/
namespace App;
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
class PHPMailerSender {
protected $mail;
protected $hasHtmlFile = false;
function __construct($addressEmail, $addressName, $subject, $htmlContentsLoc = '', $altBody){
$this->mail = new PHPMailer(true); // Passing `true` enables exceptions
//Set the subject line
$this->mail->Subject = $subject;
//Set who the message is to be sent from
//Replace the plain text body with one created manually
$this->mail->AltBody = $altBody;
//Set who the message is to be sent to
$this->mail->addAddress($addressEmail, $addressName);
$this->mail->isHTML(true); // Set email format to HTML
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
if($htmlContentsLoc){
if(file_exists($htmlContentsLoc)){
$this->hasHtmlFile = true;
$this->mail->msgHTML(file_get_contents($htmlContentsLoc), __DIR__);
}
}
}
function addHTML($html){
if(!$this->hasHtmlFile){
$this->mail->Body = $html;
}
return $this;
}
function addAttachment($attachment = []){
for ($i=0; $i < count($attachment) ; $i++) {
$this->mail->addAttachment($attachment['file']['tmp_name'][$i], $_FILES['file']['name'][$i]); // Optional name
}
return $this;
}
function send(){
try {
// Mail server settings
if( !$this->mail->send() ) {
throw new \Exception("mail not sended. unknown errors.", 500);
} else {
return true;
}
} catch (Exception $e) {
// if Could not instantiate mail function. read this :
// https://docs.mailpoet.com/article/56-could-not-instantiate-mail-function
throw $e;
}
}
function isSMTP($host = 'smtp.gmail.com', $smtpAuth = true, $username = 'your-email@gmail.com', $password = 'your-gmail-password', $smtpSecure = 'tls', $port = 587){
$this->mail->isSMTP(); // Set mailer to use SMTP
$this->mail->Host = $host; // Specify main and backup SMTP servers
$this->mail->SMTPAuth = $smtpAuth; // Enable SMTP authentication
$this->mail->Username = $username; // SMTP username
$this->mail->Password = $password; // SMTP password
$this->mail->SMTPSecure = $smtpSecure; // Enable TLS encryption, `ssl` also accepted
$this->mail->Port = $port; // TCP port to connect to
return $this;
}
function isMail(){
$this->mail->isMail(); // Set mailer to use SMTP
return $this;
}
function isSendmail(){
$this->mail->isSendmail(); // Set mailer to use SMTP
return $this;
}
function setConfig($config = []){
if(!empty($config)){
if($config['driver'] == 'smtp'){
$this->mail->isSMTP();
}elseif($config['driver'] == 'sendmail'){
$this->mail->isSendmail();
}elseif($config['driver'] == 'mail'){
$this->mail->isMail();
}else{
$this->mail->isMail();
}
//Set who the message is to be sent from
if($config['driver'] == 'smtp'){
$this->mail->Host = $config['host'] ?? $this->mail->Host; // Specify main and backup SMTP servers
$this->mail->SMTPAuth = true; // Enable SMTP authentication
$this->mail->Username = $config['username'] ?? $this->mail->Username; // SMTP username
$this->mail->Password = $config['password'] ?? $this->mail->Password; // SMTP password
$this->mail->SMTPOptions = ['ssl'=> ['allow_self_signed' => true]];
$this->mail->SMTPSecure = $config['encryption'] ?? $this->mail->SMTPSecure; // Enable TLS encryption, `ssl` also accepted
$this->mail->Port = $config['port'] ?? $this->mail->Port; // TCP port to connect to
}
$this->mail->setFrom($config['from']['address'] ?? "example@mail.com", $config['from']['name'] ?? "example");
$this->mail->addReplyTo($config['from']['address'] ?? "example@mail.com", $config['from']['name'] ?? "example");
}
return $this;
}
}
@fzn0x
Copy link
Author

fzn0x commented Mar 13, 2021

Example Usage with Blade View::render

public function sendMail($defaultBody, $isFile = false, $location = 'contents.html'){
    $mailer = new PhpMailerSender(
        'fauzandev@protonmail.com', // Receiver Address
        'fauzandev', // Receiver Address
        'Test', // Subject
        $isFile ? $location : '', // HTML FILE LOCATION
        'TEST ALTBODY' //Altbody
    );
    $mailer->setConfig($this->mailConfig);

    $mailer->addHTML($defaultBody);

    if($mailer->send()){
        return true;
    }

    return false;
}

$sended = $this->sendMail(
    view('test')
        ->render()
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment