BCA / B.Tech 8 min read

Sending Email By PHP

Sending Email By PHP in Hindi |  Sending Email in PHP in Hindi:


  • Sending an email in PHP is a simple process. The built-in mail() function in PHP can be used for this purpose. 
  • Also, for a more secure and advanced method, you can use the PHPMailer library.
Send Email By PHP in Hindi

 Here we will explain both methods in detail.

Sending email using PHP's mail() function:

This is a simple and easy method. This function can be used to send emails directly.

Example:

// Receiver's email address

// Email subject
$subject = "This is a test email";

// Email message
$message = "Hello,\n\nThis email was sent using PHP.";

// Headers (From and Reply-To)
$headers = "From: [email protected]\r\n" .
           "Reply-To: [email protected]\r\n" .
           "X-Mailer: PHP/" . phpversion();

// Send email
if (mail($to, $subject, $message, $headers)) {
    echo "Email sent successfully!";
} else {
    echo "There was a problem sending the email!";
}
?>

Note:
  • The mail() function only works when the mail service is configured correctly on the server.
  • It is used for simple tasks, but it is not highly reliable.

Sending email using PHPMailer:

PHPMailer is a popular PHP library that helps in sending emails in a secure and better way. It can be used via SMTP (Simple Mail Transfer Protocol).

Step 1: Install PHPMailer
You can install it using composer:

composer require phpmailer/phpmailer

Step 2: Write the code

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Load PHPMailer
require 'vendor/autoload.php';

// Create a PHPMailer object
$mail = new PHPMailer(true);

try {
    // SMTP setup
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com'; // SMTP server
    $mail->SMTPAuth = true;
    $mail->Username = '[email protected]'; // Your email
    $mail->Password = 'your-email-password'; // Your password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;

    // Email setup
    $mail->setFrom('[email protected]', 'Your Name');
    $mail->addAddress('[email protected]', 'Receiver Name'); // Receiver
    $mail->Subject = 'This is a PHPMailer test email';
    $mail->Body = 'Hello,\n\nThis email was sent using PHPMailer.';

    // Send email
    $mail->send();
    echo "Email sent successfully!";
} catch (Exception $e) {
    echo "There was a problem sending the email. Error: {$mail->ErrorInfo}";
}
?>
Note:

  • Correct credentials (such as username and password for Gmail) are required to use SMTP.
  • For Gmail, you may need to enable "Less Secure App Access", or use an API Key.
When to use which?

  • mail() function: If your email system is simple and basic.
  • PHPMailer: If you need to send emails in a secure and reliable way.
  • If you have any problem with the PHPMailer setup, you can ask me!