Php send mail
A classic topic!
In PHP, you can send an email using the mail()
function, which is a built-in function that allows you to send an email to one or more recipients. Here's a basic example:
<?php
$to = '[email protected]';
$subject = 'Test email';
$message = 'This is a test email sent from PHP.';
$headers = 'From: [email protected]'. "\r\n".
'Reply-To: [email protected]'. "\r\n".
'MIME-Version: 1.0'. "\r\n".
'Content-Type: text/plain; charset=UTF-8';
mail($to, $subject, $message, $headers);
?>
In this example, we're sending an email to [email protected]
with the subject "Test email" and a simple message. The $headers
variable is used to set the From, Reply-To, and Content-Type headers.
However, the mail()
function has some limitations, such as:
- It may not work with all email providers or servers.
- It may not support advanced features like attachments or HTML emails.
- It may not be secure, as it sends the email in plain text.
To overcome these limitations, you can use a PHP mail library or extension, such as:
- PHPMailer: A popular and widely-used library that provides a more robust and flexible way to send emails.
- SwiftMailer: Another popular library that provides a simple and easy-to-use API for sending emails.
- PHP's built-in
SwiftMailer
extension: This is a built-in extension that provides a simple way to send emails using the SwiftMailer library.
Here's an example using PHPMailer:
<?php
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your_password';
$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Test email';
$mail->Body = 'This is a test email sent from PHPMailer.';
$mail->send();
?>
In this example, we're using PHPMailer to send an email to [email protected]
with the subject "Test email" and a simple message. We're also setting the From, Reply-To, and Content-Type headers using the setFrom()
, addAddress()
, and Subject
methods.
Remember to install the PHPMailer library and configure your email settings accordingly.