Attach a html file with mail in php

A classic question!

In PHP, you can attach a HTML file to an email using the mail() function or a PHP mail library like PHPMailer. Here's an example using the mail() function:

<?php
// Set the email headers
$headers = 'From: Your Name <[email protected]>'. "\r\n";
$headers.= 'Content-Type: text/html; charset=UTF-8'. "\r\n";

// Set the email body
$body = '<html><body><h1>Attached HTML File</h1></body></html>';

// Set the attachment
$attachment = 'path/to/your/html/file.html';

// Send the email
mail('[email protected]', 'Subject', $body, $headers, $attachment);
?>

In this example, we set the email headers to include the Content-Type header with a value of text/html; charset=UTF-8, which tells the email client to render the email body as HTML. We then set the email body to a simple HTML string.

To attach the HTML file, we use the mail() function's fifth argument, which is an array of attachments. In this case, we pass the path to the HTML file as a string.

Note that the mail() function is a built-in PHP function, but it has some limitations, such as not being able to send attachments larger than 7MB. If you need to send larger attachments or more complex emails, consider using a PHP mail library like PHPMailer.

Here's an example using PHPMailer:

<?php
require 'PHPMailer/PHPMailer.php';
require '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 = 'Subject';
$mail->Body = '<html><body><h1>Attached HTML File</h1></body></html>';
$mail->addAttachment('path/to/your/html/file.html', 'text/html');

$mail->send();
?>

In this example, we create a new instance of the PHPMailer class and set up the email settings, such as the SMTP server and authentication credentials. We then set the email body to a simple HTML string and attach the HTML file using the addAttachment() method.

Note that you'll need to install PHPMailer and its dependencies using Composer or by downloading the library manually.