To send an email in PHP, you can use the mail() function. Here's a simple example:
php
<?php
$to = "
[email protected]";
$subject = "Test Email";
$message = "This is a test email sent from PHP.";
$headers = "From:
[email protected]";
// Send email
$mailSent = mail($to, $subject, $message, $headers);
if ($mailSent) {
echo "Email sent successfully.";
} else {
echo "Error sending email.";
}
?>
In this example:
- Replace "[email protected]" with the actual email address of the recipient.
- Replace "[email protected]" with the actual email address of the sender.
- Modify the $subject and $message variables according to your needs.
Note that the mail() function relies on the mail configuration of your server. Make sure your server is configured to send emails, or consider using a third-party library like PHPMailer or Swift Mailer for more advanced features and better control over the email sending process.
Here's an example using PHPMailer:
php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php'; // Make sure to include the autoloader from PHPMailer
$mail = new PHPMailer(true);
try {
// Server settings
$mail->isSMTP();
$mail->Host = 'smtp.example.com'; // Your SMTP server
$mail->SMTPAuth = true;
$mail->Username = 'your_username';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
// Recipients
$mail->setFrom('
[email protected]', 'Your Name');
$mail->addAddress('
[email protected]', 'Recipient Name');
// Content
$mail->isHTML(true);
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email sent from PHP using PHPMailer.';
$mail->send();
echo 'Email sent successfully.';
} catch (Exception $e) {
echo 'Error sending email: ', $mail->ErrorInfo;
}
?>
Remember to install PHPMailer using Composer (composer require phpmailer/phpmailer) before using it in your project. Adjust the settings such as SMTP server, username, password, and other parameters based on your email provider.