PHP

Sending Emails with Email Templates in PHP

If you want to send an email using an email template file in PHP without using a framework like Laravel, you can achieve it by loading the template file, replacing the placeholders with dynamic data, and using the `mail()` function to send the email. Here's an example:

1. Create an email template file called `email_template.html`:

<!-- email_template.html -->
<!DOCTYPE html>
<html>
<head>
   <title>Email Template</title>
</head>
<body>
   <h1>Hello, {name}</h1>
   <p>This is a test email.</p>
</body>
</html>

2. In your PHP code, load the email template file, replace the placeholders with dynamic data, and send the email:

<?php
// Recipient's email address
$to = "recipient@example.com";
// Email subject
$subject = "Hello from PHP!";
// Load the email template file
$template = file_get_contents("email_template.html");
// Replace placeholders with dynamic data
$name = "John Doe";
$body = str_replace("{name}", $name, $template);
// Additional headers
$headers = "From: sender@example.com\r\n";
$headers .= "Reply-To: sender@example.com\r\n";
$headers .= "CC: cc@example.com\r\n";
$headers .= "BCC: bcc@example.com\r\n";
$headers .= "Content-Type: text/html\r\n";
// Sending the email
if (mail($to, $subject, $body, $headers)) {
   echo "Email sent successfully!";
} else {
   echo "Failed to send email.";
}
?>

In this code, the `file_get_contents()` function is used to load the content of the email template file into a string variable called `$template`. Then, the `str_replace()` function replaces the `{name}` placeholder in the template with the actual name value.

Ensure that you update the email addresses and customize the dynamic data according to your needs.

Please note that the `mail()` function relies on the server's configured mail settings. Make sure your server is properly set up to send emails, and be aware that this approach may not handle advanced email requirements or provide robust error handling. Consider using a dedicated email library or service for more complex email needs.

Leave A Comment