Holla amigos.

We are showing you today a way to use the PHPmailer with a shared hosting. PHPmailer is a module that is used to send emails using SMTP. It provides a collection of functions to build and send email messages. PHPMailer supports several ways of sending email: mail(), Sendmail, qmail & direct to SMTP servers. You can use any feature of SMTP-based e-mail, multiple recepients via to, CC, BCC, etc. In short: PHPMailer is an efficient way to send e-mail within PHP.

First, add the module

download the PHPMailer from this url: Github, then include it in your project like below:


<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

Now include the classes needed in your files, check the path related to the current file and add it.

Second, usage

Now let’s call the mailer and send some emails.


<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

class MailHelper
{
public static function sendEmails($toEmails, $ccEmails, $bccEmails, $subject, $body, $embeddedImages)
    {
        $host    = Configs::getByCode('SMTP_HOST')->PValue; //getting the host or IP for SMTP
        $user    = Configs::getByCode('SMTP_USER')->PValue; //getting the username
        $pass    = Configs::getByCode('SMTP_PASS')->PValue; //getting the password
        $port    = Configs::getByCode('SMTP_PORT')->PValue; //getting the port SMTP
        $secure  = Configs::getByCode('SMTP_SECURE')->PValue; //getting the SSL parameter
        $from    = Configs::getByCode('SMTP_FROM')->PValue; //getting the sender email like showing from [email protected]
        $replyTo = Configs::getByCode('SMTP_REPLY_TO')->PValue; //getting the reply-to address
        $mail    = new PHPMailer(true); // Passing `true` enables exceptions
        try {
            
            // Server settings
            
            $mail->SMTPDebug = 2; // Enable verbose debug output
            $mail->IsSMTP(); // IsMail(); // Set mailer to use SMTP
            $mail->Host        = $host; // Specify main and backup SMTP servers
            $mail->SMTPAuth    = true; // Enable SMTP authentication
            $mail->Username    = $user; // SMTP username
            $mail->Password    = $pass; // SMTP password
            $mail->SMTPSecure  = $secure; // Enable TLS encryption, `ssl` also accepted
            $mail->Port        = $port; // TCP port to connect to
            $mail->SMTPOptions = array(
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                )
            );
            // Recipients
            
            $mail->setFrom($from);
            if ($toEmails == null || !$toEmails) {
                $mail->addAddress($replyTo); // Add a recipient
            } else {
                $mail->addReplyTo($replyTo);
            }
            if ($toEmails != null) {
                foreach ($toEmails as $e) {
                    $mail->addAddress($e);
                }
            }
            
            if ($ccEmails != null) {
                foreach ($ccEmails as $e) {
                    $mail->addCC($e);
                }
            }
            
            if ($bccEmails != null) {
                foreach ($bccEmails as $e) {
                    $mail->addBCC($e);
                }
            }
            
            if ($embeddedImages != null) {
                foreach ($embeddedImages as $embI) {
                    $body = str_replace('cid:' . $embI->CID . '', $GLOBALS['home_url'] . $embI->Path, $body);
                    //error_log(dirname(__DIR__) . $embI->Path);
                    //$mail->AddEmbeddedImage(dirname(__DIR__) .$embI->Path, $embI->CID, $embI->Name);
                }
            }
            
            // //Attachments
            // $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
            // $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
            // Content
            //$mail->Body = 'Your <b>HTML</b> with an embedded Image: <img src="cid:my-attach"> Here is an image!';
            $mail->isHTML(true); // Set email format to HTML
            $mail->Subject = $subject;
            
            //$mail->MsgHTML($body, dirname(__DIR__));
            
            $mail->Body    = $body;
            $mail->AltBody = $body;
            
            //$mail->preSend();
            //$message = $mail->getSentMIMEMessage();
            //error_log($message);
            if (!$mail->send()) {
                error_log("Error sending: " . $mail->ErrorInfo);
                error_log('Message has not been sent');
            } else {
                error_log('Message has been sent');
            }
        }
        
        catch (Exception $e) {
            error_log('Message could not be sent. Mailer Error: ' . $mail->ErrorInfo);
            error_log('sendEmails. Mailer Error: ' . $e->getMessage());
        }
    }
}

So using this simple class is enough to send awesome emails via PHPMailer, you can add attachments, send to BCCs, CCs and embed images inside the body.

Stay tuned for more posts 🙂

Categories: PHP