Mail with php

PHP provides several ways to send emails using various libraries and functions. Here are some of the most common methods:

  1. PHP's built-in mail function: PHP has a built-in mail() function that allows you to send emails using a simple syntax. However, this function is not recommended as it is not reliable and can be affected by server settings.

Example:

<?php
$to = '[email protected]';
$subject = 'Test email';
$message = 'This is a test email';
$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);
?>
  1. PHPMailer: PHPMailer is a popular PHP library that provides a more robust and flexible way to send emails. It supports multiple email protocols, including SMTP, POP3, and IMAP.

Example:

<?php
require_once 'PHPMailer/PHPMailer.php';
require_once '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';

if (!$mail->send()) {
    echo 'Error sending email: '. $mail->ErrorInfo;
} else {
    echo 'Email sent successfully!';
}
?>
  1. SwiftMailer: SwiftMailer is another popular PHP library that provides a simple and easy-to-use way to send emails. It supports multiple email protocols and has a lot of features out of the box.

Example:

<?php
require_once 'SwiftMailer/Swift.php';

$mail = new Swift_Mailer();
$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 'Error sending email: '. $mail->ErrorInfo;
} else {
    echo 'Email sent successfully!';
}
?>
  1. PEAR Mail: PEAR Mail is a PHP library that provides a simple way to send emails using the PEAR package manager.

Example:

<?php
require_once 'Mail.php';

$mail = Mail::factory('smtp', array(
    'host' => 'smtp.example.com',
    'port' => 587,
    'auth' => true,
    'username' => '[email protected]',
    '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';

if (!$mail->send()) {
    echo 'Error sending email: '. $mail->ErrorInfo;
} else {
    echo 'Email sent successfully!';
}
?>

These are just a few examples of how you can send emails using PHP. The choice of library or function depends on your specific needs and requirements.