Sending mail in PHP – avoid sending to “junk” folder


by in Web Development


We all know that PHP is great for back-end development. However, some functions can be tricky to fine tune for the best web development possible.

The mail() function has a high probability of sending mail to user’s “junk” or spam folders because the connection was not authenticated.

To avoid that, use the following function below. This assumes you have PEAR setup and working properly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
 require_once "Mail.php";
 
 $from = "Sandra Sender <sender@example.com>";  $to = "Ramona Recipient <recipient@example.com>";  $subject = "Hi!";  $body = "Hi,nnHow are you?";
 
 $host = "mail.example.com";
 $username = "smtp_username";
 $password = "smtp_password";
 
 $headers = array ('From' => $from,
   'To' => $to,
   'Subject' => $subject);
 $smtp = Mail::factory('smtp',
   array ('host' => $host,
     'auth' => true,
     'username' => $username,
     'password' => $password));
 
 $mail = $smtp->send($to, $headers, $body);
 
 if (PEAR::isError($mail)) {
   echo("<p>" . $mail->getMessage() . "</p>");
  } else {
   echo("<p>Message successfully sent!</p>");
  }
 ?>

Please, rate this post:

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00)
Loading...

Discussion (1)


  • Chris

    Nice post Dario. There are also a few other tricks I’ve figured out when having to deal with the dreaded spam folder: Setup reverse DNS, setup an SPF record, and in some cases you have to contact the spam team of companies like AOL, Hotmail, Verizon and others proving to them your SMTP server is legit.

    Reply