SMTP (Simple Mail Transfer Protocol) is the standard protocol for email transmission over the internet. Using SMTP, PHP developers can send emails that include text, attachments, and even images.
PHPMailer is a widely-used PHP library for sending emails, supporting SMTP and various email formats. You can install PHPMailer using Composer with the following command:
<span class="fun">composer require phpmailer/phpmailer</span>
After installation, include the autoload file in your PHP script to use the PHPMailer class:
<span class="fun">require 'vendor/autoload.php';</span>
Create a PHPMailer instance and set SMTP server details, including server address, authentication, and encryption method:
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your-password';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
Please replace the SMTP server address, username, and password above with your actual information.
Specify the sender, recipient, subject, and body of the email:
$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email.';
Call the send() method to send the email and handle the result with a message:
if ($mail->send()) {
echo 'Email sent successfully.';
} else {
echo 'Email sending failed. Error: ' . $mail->ErrorInfo;
}
require 'vendor/autoload.php';
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your-password';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email.';
if ($mail->send()) {
echo 'Email sent successfully.';
} else {
echo 'Email sending failed. Error: ' . $mail->ErrorInfo;
}
This article demonstrated how to send emails via SMTP in PHP using the PHPMailer library. It included all steps from installing the library, including classes, configuring SMTP settings, to setting email content and sending emails. With these skills, you can easily integrate email functionality into your PHP projects.