2

I'm sending an email via PHP's mail() function. In the message I set a link that looks like this:

$message = "<a href='". $link. "'>" .$title. "</a>\n\n";

However, when the email is received, the email body shows the html code instead of the title as a hyperlink. I'm not very familiar with html emails. How could I achieve what I am trying to get?

jordan
  • 9,570
  • 9
  • 43
  • 78

3 Answers3

11

Try to add an header, so that the mail client doesn't believe it is plain text:

$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";

See PHP mail function manual:

Example #4 Sending HTML email:

<?php
// multiple recipients
$to  = 'aidan@example.com' . ', '; // note the comma
$to .= 'wez@example.com';

// subject
$subject = 'Birthday Reminders for August';

// message
$message = '
<html>
<head>
  <title>Birthday Reminders for August</title>
</head>
<body>
  <p>Here are the birthdays upcoming in August!</p>
  <table>
    <tr>
      <th>Person</th><th>Day</th><th>Month</th><th>Year</th>
    </tr>
    <tr>
      <td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
    </tr>
    <tr>
      <td>Sally</td><td>17th</td><td>August</td><td>1973</td>
    </tr>
  </table>
</body>
</html>
';

// 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' . "\r\n";

// Additional headers
$headers .= 'To: Mary <mary@example.com>, Kelly <kelly@example.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <birthday@example.com>' . "\r\n";
$headers .= 'Cc: birthdayarchive@example.com' . "\r\n";
$headers .= 'Bcc: birthdaycheck@example.com' . "\r\n";

// Mail it
mail($to, $subject, $message, $headers);
?>
Jean
  • 7,623
  • 6
  • 43
  • 58
3

Please see the documentation for PHP mail() at http://php.net/manual/en/function.mail.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' . "\r\n";

// Additional headers
$headers .= 'To: Mary <mary@example.com>, Kelly <kelly@example.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <birthday@example.com>' . "\r\n";
$headers .= 'Cc: birthdayarchive@example.com' . "\r\n";
$headers .= 'Bcc: birthdaycheck@example.com' . "\r\n";

// Mail it
mail($to, $subject, $message, $headers);

Although it's generally recommended to avoid using mail() alone.

You should consider using PHPMailer, for example.

Adrian
  • 1,046
  • 7
  • 12
1

You have to tell the e-mail client that there is an HTML portion to the e-mail. I'd recommend something like Swiftmailer to do the work instead of doing everything yourself.

dragonmantank
  • 15,243
  • 20
  • 84
  • 92