Send Email using SMTP
Pre-requisites: Basic Understanding HTML, PHP and OOP.
In this project:
- Send an email using SMTP.
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output
$mail->isSMTP(); //Send using SMTP
$mail->Host = 'smtp.example.com'; //Set the SMTP server to send through
$mail->SMTPAuth = true; //Enable SMTP authentication
$mail->Username = '[email protected]'; //SMTP username
$mail->Password = 'pwd'; //SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption
$mail->Port = 465;
//TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
//Recipients
$mail->setFrom('[email protected]', 'Mailer');
$mail->addAddress('[email protected]', 'Smith'); //Add a recipient
$mail->addAddress('[email protected]'); //Name is optional
$mail->addReplyTo('[email protected]', 'Message');
$mail->addCC('[email protected]');
$mail->addBCC('[email protected]');
//Attachments
$mail->addAttachment('/var/tmp/file.tar.gz'); //Add attachments
$mail->addAttachment('/tmp/image.jpeg', 'new.jpeg'); //Optional name
//Content
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = 'Mail subject';
$mail->Body = 'HTML message body';
$mail->AltBody = 'Message body in plain text';
$mail->send();
echo 'Message is sent';
} catch (Exception $e) {
echo "Message is not sent. Error: {$mail->ErrorInfo}";
}
?>
Code Explanation of mail.php |
|
|
|
|
|
|
Summary
In this project, we have learned to send an email using SMTP.
Predefined classes are imported and an instance of PHPMailer is created and is used to define the mail parameters and finally then mail is sent using send()
method.