With the development of the Internet, email has become an important tool for daily communication. In web development, sending emails using PHP is a common requirement. This article explains how to develop a simple email sending function using PHP and PHPMailer, with complete example code.
First, create a PHP file on the server to handle the email sending function. For example, name it sendmail.php.
PHPMailer is a popular library that simplifies email sending by providing convenient APIs. Download the PHPMailer library, extract it into your project directory, and include the necessary files in sendmail.php:
require 'PHPMailer/Exception.php'; require 'PHPMailer/PHPMailer.php'; require 'PHPMailer/SMTP.php';
Use PHPMailer APIs in sendmail.php to implement the email sending function:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
// Instantiate PHPMailer object
$mail = new PHPMailer(true);
try {
// Set SMTP server information
$mail->SMTPDebug = 0; // Disable debug mode
$mail->isSMTP(); // Use SMTP to send
$mail->Host = 'smtp.example.com'; // SMTP server address
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'your-email@example.com'; // SMTP username
$mail->Password = 'your-password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Use TLS encryption
$mail->Port = 587; // SMTP port
// Set sender information
$mail->setFrom('from@example.com', 'Sender Name');
// Set recipient information
$mail->addAddress('to@example.com', 'Recipient Name');
// Set email subject and body
$mail->isHTML(true);
$mail->Subject = 'Email Subject';
$mail->Body = '<h1>Email Body</h1><p>This is a test email.</p>';
// Send the email
$mail->send();
echo 'Email sent successfully';
} catch (Exception $e) {
echo 'Email sending failed: ' . $mail->ErrorInfo;
}In this code, the SMTP server address, username, and password are used to configure the SMTP information. setFrom() sets the sender information, addAddress() sets the recipient information. isHTML() sets the email body to HTML format, then the Subject and Body are set, and finally send() is called to send the email.
Open sendmail.php in a browser. If the email is sent successfully, it will display "Email sent successfully". If there is an error, it will display "Email sending failed" along with detailed error information.
This article introduces the complete process of sending emails using PHP and the PHPMailer library, including SMTP configuration, sender and recipient setup, email subject and body, as well as sending and testing the email. PHPMailer makes it easy to implement email sending, meeting the email requirements in web development.