Sending Email with Attachment using PHPMailer in PHP

By CampCodes Administrator

Updated on:

phpmailer

Getting Started

I’ve used CDN for Bootstrap in this tutorial, so you need an internet connection for it to work. If ever you want full documentation of this plugin, you can visit Github.

Installing the PHPMailer using Composer

If you don’t have Composer yet, you may use this link to download the latest version.

1. Create a folder of your app, in my case I’ve created my app inside htdocs folder of my xampp and name it phpmailer.

2. Create a file named Composer, JSON inside your app folder and put the ff. Line inside it. This will tell Composer to install phpmailer to our app.

{
     "phpmailer/phpmailer": "~6.0"
}
composerjson
3. Open command prompt, navigate to your app and type the ff.
composer require phpmailer/phpmailer

This will install PHPMailer for our app.

4. After installation, you should be able to see the vendor folder.

Creating a Send Email Form

Next, we’re going to create a form to send email using PHPMailer, and this will be our index.php.

<?php
    session_start();
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Sending Email using PHPMailer</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <h1 class="page-header text-center">Sending Email using PHPMailer</h1>
    <div class="row">
        <div class="col-sm-4 col-sm-offset-4">
            <?php
                if(isset($_SESSION['message'])){
                    ?>
                    <div class="alert alert-info text-center">
                        <?php echo $_SESSION['message']; ?>
                    </div>
                    <?php
 
                    unset($_SESSION['message']);
                }
            ?>
            <form method="POST" action="send.php" enctype="multipart/form-data">
                <div class="form-group">
                    <label>Email:</label>
                    <input type="email" class="form-control" name="email" required>
                </div>
                <div class="form-group">
                    <label>Subject:</label>
                    <input type="text" class="form-control" name="subject" required>
                </div>
                <div class="form-group">
                    <label>Message:</label>
                    <textarea class="form-control" name="message" required></textarea>
                </div>
                <div class="form-group">
                    <label>Add Attachment:</label>
                    <input type="file" name="attachment">
                </div>
                <button type="submit" name="send" class="btn btn-primary">Send</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>

Creating a Send Email Code

This contains our code that sends email using PHPMailer, and we’re going to name it as send.php.

READ ALSO:   Delete Multiple Table Row In SQLite using PHP

<?php
// 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;
 
session_start();
 
if(isset($_POST['send'])){
 
    $email = $_POST['email'];
    $subject = $_POST['subject'];
    $message = $_POST['message'];
 
    $filename = $_FILES['attachment']['name'];
    $location = 'attachment/' . $filename;
    move_uploaded_file($_FILES['attachment']['tmp_name'], $location);
 
    //Load composer's autoloader
    require 'vendor/autoload.php';
 
    $mail = new PHPMailer(true);                              // Passing `true` enables exceptions
    try {
        //Server settings
        $mail->isSMTP();                                      // Set mailer to use SMTP
        $mail->Host = 'smtp.gmail.com';                       // Specify main and backup SMTP servers
        $mail->SMTPAuth = true;                               // Enable SMTP authentication
        $mail->Username = 'testcampcodes@gmail.com';     // Your Email/ Server Email
        $mail->Password = 'mysourcepass';                     // Your Password
        $mail->SMTPOptions = array(
            'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
            )
        );                         
        $mail->SMTPSecure = 'ssl';                           
        $mail->Port = 465;                                   
 
        //Send Email
        $mail->setFrom('testsourcecodester@gmail.com');
 
        //Recipients
        $mail->addAddress($email);              
        $mail->addReplyTo('testsourcecodester@gmail.com');
 
        //Attachment
        if(!empty($filename)){
            $mail->addAttachment($location, $filename); 
        }
 
        //Content
        $mail->isHTML(true);                                  
        $mail->Subject = $subject;
        $mail->Body    = $message;
 
        $mail->send();
        $_SESSION['message'] = 'Message has been sent';
    } catch (Exception $e) {
        $_SESSION['message'] = 'Message could not be sent. Mailer Error: '.$mail->ErrorInfo;
    }
 
    header('location:index.php');
}
else{
    $_SESSION['message'] = 'Please fill up the form first';
    header('location:index.php');
}

Allowing Less Secure Apps

Lastly, in our server email, we need to allow less secure apps by logging in your server email and use this link.

P.S. Don’t forget to create an attachment folder in our app folder. This will be the container for our uploaded attachments. Also, take note of Gmails restrictions in sending emails with attachments.

That ends this tutorial, Happy Coding!

Download Here

Leave a Comment