phpmailerHow do I use PHPMailer for sending emails?
PHPMailer is a popular open source library for sending emails with PHP. To use it, you will need to install it using Composer:
composer require phpmailer/phpmailer
Once installed, you can use the following code to send an email:
<?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;
//Load Composer's autoloader
require 'vendor/autoload.php';
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '[email protected]'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('[email protected]', 'Mailer');
$mail->addAddress('[email protected]', 'Joe User'); // Add a recipient
$mail->addAddress('[email protected]'); // Name is optional
$mail->addReplyTo('[email protected]', 'Information');
$mail->addCC('[email protected]');
$mail->addBCC('[email protected]');
//Attachments
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
Output example
Message has been sent
The code above does the following:
- Imports the PHPMailer classes into the global namespace.
- Loads the Composer autoloader.
- Sets the SMTP server settings.
- Sets the recipient information.
- Attaches any files.
- Sets the email format to HTML.
- Sets the subject and body of the email.
- Sends the email.
If successful, it will output Message has been sent
.
For more information, see the PHPMailer documentation.
More of Phpmailer
- How do I configure the timeout settings for PHPMailer?
- How can I use PHPMailer without SMTP secure?
- How do I use PHPMailer to attach a ZIP file?
- How do I determine which version of PHPMailer I'm using?
- How can I use PHPMailer with React?
- How can I configure PHPMailer to support Polish characters?
- How can I configure PHPMailer to work with GoDaddy?
- How can I use PHPMailer to send emails with a Yahoo account?
- How can I send emails using PHPMailer without using SMTP?
- How do I use PHPMailer to encode emails in UTF-8?
See more codes...