PHP Send Email
Learn how to send emails in PHP using the mail()
function and with PHPMailer
for advanced SMTP emailing.
PHP में mail()
फंक्शन और PHPMailer
का उपयोग करके ईमेल भेजना सीखें।
Simple mail() function
This method sends a plain text email using the PHP mail function.
यह तरीका PHP के mail फंक्शन का उपयोग करता है और केवल साधारण ईमेल भेजता है।
<?php
$to = "user@example.com";
$subject = "Test Email";
$message = "Hello! This is a test email.";
$headers = "From: admin@example.com";
if (mail($to, $subject, $message, $headers)) {
echo "Email sent successfully.";
} else {
echo "Email sending failed.";
}
?>
PHPMailer via SMTP
Use PHPMailer for HTML emails, attachments, and SMTP server configuration.
SMTP सर्वर के माध्यम से HTML ईमेल और अटैचमेंट भेजने के लिए PHPMailer का उपयोग करें।
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_email@gmail.com';
$mail->Password = 'your_app_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('your_email@gmail.com', 'LiveCodeProgramming');
$mail->addAddress('recipient@example.com');
$mail->isHTML(true);
$mail->Subject = 'SMTP Email Test';
$mail->Body = '<b>Hello</b>, this is a test email via PHPMailer';
$mail->send();
echo 'Email has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Error: {$mail->ErrorInfo}";
}
?>
Email Validation
Always validate user email input.
हमेशा उपयोगकर्ता के ईमेल इनपुट को वैलिडेट करें।
<?php
$email = $_POST['email'];
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email address.";
} else {
echo "Invalid email address.";
}
?>