Send mail using php
Here is an example of how to send an email using PHP:
Using the mail()
function
<?php
$to = '[email protected]';
$subject = 'Test email';
$message = 'This is a test email sent using 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);
?>
This code uses the mail()
function to send an email to the recipient. The function takes four arguments:
$to
: the email address of the recipient$subject
: the subject of the email$message
: the body of the email$headers
: an array of headers to be included in the email
Using a PHP mail library
<?php
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.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->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Test email';
$mail->Body = 'This is a test email sent using PHPMailer.';
$mail->send();
?>
This code uses the PHPMailer library to send an email. You'll need to download and install the library, and then include it in your PHP script.
Using a PHP mail class
<?php
class Mail {
public function send($to, $subject, $message) {
$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);
}
}
$mail = new Mail();
$mail->send('[email protected]', 'Test email', 'This is a test email sent using a PHP mail class.');
?>
This code defines a simple mail class that has a send()
method. You can use this class to send emails by creating an instance of the class and calling the send()
method.
Common issues
- Make sure that the email address you're sending to is valid and exists.
- Check that your email server is configured correctly and that you have the necessary permissions to send emails.
- Make sure that the
mail()
function is enabled in your PHP configuration. You can check this by running the following code:phpinfo();
and looking for themail()
function in the output. - If you're using a PHP mail library or class, make sure that you've installed and configured it correctly.