How to Send Attachments using PHPMailer

How to Send Attachments using PHPMailer

In this article we will learn how to send attachments in an email or email using for her class PHPMailer .

It can also be done with the mail () PHP function but is not as reliable function and lacks some features such as sending HTML content or images with PHPMailer can achieve with simple lines of code.

In the example that we will illustrate going to have a form in which we will only provide data, the destination email which we will send the email with the attachment.

<form action = "index.php" method = "post">
<h3> Send yourself an email with attachment </ h3>
        <td> Email: </ td>
        <td> <input type = "text" name = "email" value = "<? = $ _ POST [ 'email']?>"> </ td>
        <td> <input type = "submit" name = "receive" value = "Receive email" /> </ td>
    </ tr>
</ table>
</ form>

A simple form with a single field and is processed by the tracional method using the POST method.

The code that receives data from this form will be as follows:

<? php
check_email function ($ email) {
    return (filter_var ($ email, FILTER_VALIDATE_EMAIL))? 1: 0;

if (isset ($ _ POST [ 'receive'])) {
    if (check_email ($ _ POST [ 'email'])) {
        require_once ( "classes / class.phpmailer.php");
        $ mail = new PHPMailer ();
        $ mail-> From = "";
        $ mail-> FromName = "LucidKit";
        $ mail-> Subject = "Demo PHPMailer";
        $ mail-> Body = "Hi, this is a demo of sending emails with attachments !!!";
        $ mail-> AddAddress ($ _ POST [ 'email'], "User Name");
        $ file = 'file.pdf';
        $ mail-> AddAttachment ($ file, $ file);
        $ mail-> Send ();
        echo '<p> You have successfully sent the email to' $ _ POST [ 'email'] '</ p>'..;
    else {
        echo '<p> The email entered is incorrect </ p>';

In this case, we are somewhat cautious and have a function to verify that the email entered meets pattern emails.

After clicking the submit button on the form is found that email complies with the pattern of emails and if successful include the phpMailer class and create an instance, assign some attributes of the class as they are from, From, Name, Subject, Body … add the destination email and attach the file, in this case a test PDF file.

View on GitHub

Lucid Kit

Related Posts
Leave a reply
Captcha Click on image to update the captcha .