Sending multipart/alternative with PHP mail()
html-email, multipart-alternative, php
Solution
I should of course tell you to use a library for this, such as swift, but I think this is a good exercise so I'll tell you what's wrong with it :)
It's because your line endings are wrong. Unless otherwise specified, line endings in email messages are CRLF (`\r\n`), whereas your `ob_start()` block is likely to only have LF (`\n`) as the line separator.
This causes GMail to misinterpret the email message and shows nothing instead. In my case it shows an empty download file ;)
Problem
So I am trying to send a fairly simple HTML email using PHP. I have spent the last three days trying to find a good solution and think I found one, but when I test it, it doesn't send properly. I borrowed this code from one of the tutorials I was referencing. The test code is as follows: ``` <?php //define the receiver of the email $to = 'myemail@gmail.com'; //define the subject of the email $subject = 'Test HTML email'; //create a boundary string. It must be unique //so we use the MD5 algorithm to generate a random hash $random_hash = md5(date('r', time())); //define the headers we want passed. Note that they are separated with \r\n $headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com"; //add boundary string and mime type specification $headers .= "\r\nContent-Type: multipart/alternative; boundary=\"".$random_hash."\""; //define the body of the message. ob_start(); //Turn on output buffering ?> --<?php echo $random_hash; ?> Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Hello World!!! This is simple text email message. --<?php echo $random_hash; ?> Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: 7bit <h2>Hello World!</h2> <p>This is something with <b>HTML</b> formatting.</p> --<?php echo $random_hash; ?>-- <? //copy current buffer contents into $message variable and delete current output buffer $message = ob_get_clean(); //send the email $mail_sent = @mail( $to, $subject, $message, $headers ); //if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" echo $mail_sent ? "Mail sent" : "Mail failed"; ?> ``` The problem is that, although it sends the email just fine, it either sends it as plain text, or a blank message in Gmail. Any ideas why?