Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending HTML email using PHP: including the HTML file

Tags:

html

php

email

I am trying to send email using PHP. The email is an HTML email with hundreds of line of HTML code (in file email.html). I don't want to write the whole HTML code in the PHP. How can I do it? Is my below method correct? Any better alternative?

My Code (PHP):

$email_text = file_get_contents('email.html');
$headers = "From:[email protected]";

mail('[email protected]', 'Hello', $email_text, $headers);

My Email File (email.html):

<html>
     <body>
          <a href="http://google.com">Hello</a>
     </body>
</html>

My problem: I want to send an HTML email which will display HTML content. The HTML content is taken from a file called email.html.

Note 1: I have simplified my above code just for the clarity. Original code is having headers which will display HTML code correctly. Also the original HTML file is having hundreds of line and CSS styling. I have mentioned only few lines just to simplify.

Note 2: There are many duplicates of sending email using PHP but I couldn't find how to include a big HTML file in just one line of PHP code.

like image 590
sumit Avatar asked Jul 02 '12 20:07

sumit


People also ask

How can I put a HTML link inside an email body in PHP?

You need to specify a Content Type of HTML in your function. // To send HTML mail, the Content-type header must be set $headers = 'MIME-Version: 1.0' . "\r\n"; $headers . = 'Content-type: text/html; charset=iso-8859-1' .

How do you send HTML form content to email?

Complete HTML/CSS Course 2022 To send an email using HTML forms, you need to add the email id to the action attribute of the form. In that, add email proceeding with mailto: i.e. mailto:[email protected].

How do I send HTML email from my website?

Copy the entire content of a page, either with Ctrl+A (Windows) / Cmd+A (Mac) or just use a mouse or a trackpad. Then, insert it into your Gmail's compose window and send it! The email should arrive in exactly the same shape as it was last seen leaving your inbox.


1 Answers

Update for updated question:

If you don't want to include all that HTML in your PHP code, then yes file_get_contents() is a fine alternative.


You need to include the content type, and MIME version in the headers. This is charset UTF-8 also.

$headers = "From: $from <$from_email>\r\n". 
           "MIME-Version: 1.0" . "\r\n" . 
           "Content-type: text/html; charset=UTF-8" . "\r\n";

http://php.net/manual/en/function.mail.php

like image 50
David Avatar answered Sep 30 '22 02:09

David