Could we help you? Please click the banners. We are young and desperately need the money
Often you need to send mails from you application or website. This can be done through the PHP mail() function. However the standard PHP mail() function is not providing any assistance for encryption, authentication, HTML messages or attachments.
You can download the PHPMailer ZIP-file directly from the creators GitHub.
After you've unzipped the PHPMailer you can create a folder "includes" in your PHP-project (if you not already have one) and inside of the "includes"-directory paste the folder PHPMailer.
In your PHP-file, which should act as the "mail-sender", you need to load each class file manually with the code lines you see below:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
In the example below, you can see the basic usage of PHPMailer with all basic functionalities. You can send mails to multiple adresses, add attachments and send mails as HTML:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
//Create an instance; When passing "true" you enable debugging
$mail = new PHPMailer(true);
try {
//Set the mail server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'user@example.com';
$mail->Password = 'password';
$mail->SMTPSecure = 'TLS';
$mail->Port = '587';
$mail->Charset = 'UTF-8';
//Set the recipients for the mail
$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('joel@example.com', 'Joel User');
$mail->addAdress('janine@example.com'); //The second parameter for setting the name is optional
$mail->addReplyTo('info@example.com', 'Info'); //If the recipient replies to the mail, it will automatically use this address as reply-address
$mail->addCC('cc@example.com');
//Set the mail-attachements
$mail->addAttachment('/var/tmp/file.tar.gz');
$mail->addAttachment('/var/tmp/image.jpg', 'new_image.jpg');
//Set the content of the mail
$mail->isHTML(true); //Set the mail format to HTML
$mail->Subject = 'This is the subject';
$mail->Body = 'This is a HTML message body <b>I can use tags</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML clients';
//Sending the mail
$mail->send();
echo 'Mail has been sent';
} catch(Exception $e) {
echo "Message could not be send: {$mail->ErrorInfo}";
}
Now your PHPMailer is ready to go and you can start sending mails with your application!