How to use PHPMailer Library for Sending Attachments With Emails

PHPMailer is a great library if you are looking for a quick email sending setup. For some it might be a little over the top if you are used to using the highly dependable mail() function.

Just download the library from their Github here and copy it in your setup. You can as well get code snippets here.

Be a little careful about the path, otherwise that is pretty much that you’d need to do. Look for error_log for any path related misconfigurations.

The following declarations go on the top:

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

require $_SERVER['DOCUMENT_ROOT'].'/tgapp/assets/PHPMailer/src/Exception.php';
require $_SERVER['DOCUMENT_ROOT'].'/tgapp/assets/PHPMailer/src/PHPMailer.php';
require $_SERVER['DOCUMENT_ROOT'].'/tgapp/assets/PHPMailer/src/SMTP.php';

//  The actual code abstracted to a function
newEmail('work@abc.co');

Now the actual function

function newEmail($email) {
    //  Create an instance; passing 'true' enables exceptions
    $mail = new PHPMailer(true);
    
    try {
        
        $message='
                <html><body>
	                <h1>Hello there!</h1>
	                <p>Let us work together.</h2>
                </body></html>     
                 ';
        
        
        $mail->setFrom('tushar@tushargoel.com', 'Tushar Goel');
        $mail->addAddress($email);     //Add a recipient
    
        //  Attachments
        $filename = 'downloads/tushar-resume.pdf';
        $mail->addAttachment($filename);
    
        //  Content
        $mail->isHTML(true);	//Set email format to HTML
        $mail->Subject = 'Tushar - resume';
        $mail->Body    = $message;
    
        $mail->send();

        error_log('Message has been sent');
        
        return true;
    } catch (Exception $e) {
        error_log("Message could not be sent. Mailer Error: {$mail->ErrorInfo}");
        
        return false;
    }
}
comments powered by Disqus