PHP - send email with attachment example

  • Install composer if doesn't already exists
  • Install phpmailer library with command - composer require phpmailer/phpmailer
  • Copy the code from above and paste it into your index.php file
  • Execute created file with command - php index.php
require 'vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;

$email = new PHPMailer(true);

try {
    $email->Subject = 'Cartoon';
    $email->Body = 'Hello Tom!.';
    $email->AddAttachment('path/to/file.pdf', 'fileName.pdf');
    $email->setFrom('yourmail@gmail.com', 'Jerry');
    $email->addAddress('clientmail@mail.ru', 'Tom');
    $email->send();
} catch (PHPMailer\PHPMailer\Exception $e) {
    echo $e->errorMessage();
} catch (\Exception $e) {
    echo $e->getMessage();
}