PHP Send Email Using Authenticated SMTP Mail Server In Real Time

by Vivek Gite · 45 comments

PHP has mail() function to send an email to users. However this mail() will not work:

=> If sendmail (or compatible binary) is not installed

=> If Apache Web server / Lighttpd running in chrooted jail

=> And your smtp server needs an authentication before sending an email

=> Or you just need to send email using PHP PEAR

In all these cases you need to use PHP PEAR's Mail:: interface. It defines the interface for implementing mailers under the PEAR hierarchy, and provides supporting functions which are useful in multiple mailer backends. In this tip you will learn about how to send an e-mail directly to client smtp server in real time.

PHP Pear's Mail.php is located in /usr/share/pear/ directory. Following is sample code to send an email via authenticated smtp server.

PHP send email using PHP SMTP mail Pear functions - Sample source code

Following code is well commented, you need to make necessary changes as per your setup.

<?php
include("Mail.php");
/* mail setup recipients, subject etc */
$recipients = "feedback@yourdot.com";
$headers["From"] = "user@somewhere.com";
$headers["To"] = "feedback@yourdot.com";
$headers["Subject"] = "User feedback";
$mailmsg = "Hello, This is a test.";
/* SMTP server name, port, user/passwd */
$smtpinfo["host"] = "smtp.mycorp.com";
$smtpinfo["port"] = "25";
$smtpinfo["auth"] = true;
$smtpinfo["username"] = "smtpusername";
$smtpinfo["password"] = "smtpPassword";
/* Create the mail object using the Mail::factory method */
$mail_object =& Mail::factory("smtp", $smtpinfo);
/* Ok send mail */
$mail_object->send($recipients, $headers, $mailmsg);
?>

Sending smtp email from chrooted Apache or Lighttpd webserver

Read following section, if you are running a secure chrooted Apache or Lighttpd web server. I have already written about setting php mail() function in chrooted jail. If you are using chrooted jail server setup, copy all files from /usr/share/pear directory to /chroot-directory/usr/share/pear directory. For example if lighttpd chrooted jail located in /webroot directory, you need to type following commands to install PHP pear support:
# mkdir -p /webroot/usr/share/pear
# cd /webroot/usr/share/pear
# cp -avr /usr/share/pear .

If PHP SAFE MODE is on, you must set /webroot/usr/share/pear directory permission to webserver username to allow access. Otherwise you will see error as follows:

1-Nov-2006 09:43:19] PHP Warning:  main(): SAFE MODE Restriction in effect.  The script whose uid is 506 is not allowed to access /usr/share/pear/PEAR.php owned by uid 0 in /usr/share/pear/Mail.php on line 636.

So if webserver username is lighttpd or apache use following command to setup correct ownership:
# chown lighttpd:lighttpd /webroot/usr/share/pear -ROR# chown apache:apache /webroot/usr/share/pear -R

You may also find modified wordpress WP-ContactForm plugin useful. It is a drop in form for users to contact you. It can be implemented on a page or a post. Original authored by Ryan Duff, which use php mail() function to send email. I have modified the same to send email via my ISP authenticated gateway using PHP PEAR's Mail:: interface :D

Featured Articles:

Want to read Linux tips and tricks, but don't have time to check our blog everyday? Subscribe to our daily email newsletter to make sure you don't miss a single tip/tricks. Subscribe to our weekly newsletter here!

{ 45 comments… read them below or add one }

1 Loren Dorez 01.27.07 at 11:02 pm

Im currently working on a PHP Mail File.. Essentiall it needs to log into a webbased mail account like ‘Outlook Web Access’. All tutorials i see you a submit button to the caling and send of the php file. Can i use the onclick evern like such

onClick=”send_Email.php3″

or must i use a sbumit button for the form. A submit buttons doesnt work with the current setup but i could model it to if it is neccessary..

2 subhendu das 01.29.07 at 7:51 am

i need help for windows environment.
i use php triad 4.0.1

3 subhendu das 01.29.07 at 7:53 am

How i configure smtp server.
i need help for windows environment.
i use php triad 4.0.1

4 nixcraft 01.30.07 at 12:50 pm

subhendu,

I don’t use Windows so I have no idea about Windows SMTP server configuration.

5 gurjeet singh 02.02.07 at 9:54 am

hi i got this error

Warning: main(Mail.php): failed to open stream: No such file or directory in /home/meresaja/public_html/mailtest.php on line 2

Fatal error: main(): Failed opening required ‘Mail.php’ (include_path=’.:/usr/lib/php:/usr/local/lib/php’) in /home/meresaja/public_html/mailtest.php on line 2

any body help me

6 niteen 02.07.07 at 5:14 pm

you need to install pear in your server

http://pear.php.net/package/Mail

7 Vincent 02.19.07 at 4:00 pm

Ok I would like to hide the SMTP authentication from the web directory i.e. put it out of the path of public html, how would I call the functions for authentication in this case, also I want to e.mail the details of a form before it is posted or as it is being posted…..

8 nixcraft 02.20.07 at 4:46 am

PHP is server side technology; as long as it is configured properly no one is going to see your SMTP authentication information.

9 Sia.G 03.31.07 at 12:02 pm

Ok so my mailtest.php seems to have worked as I get my confirmation message. I just never receive the e-mail. ANyone know what’s going on?

10 Jackie 05.08.07 at 3:59 pm

Hello,
I’ve been trying to send emails using the PHP mail() function but it looks like the mails are not being sent. What do I need to configure on my windows server to get it to work?

11 Mateus Pezzin 05.23.07 at 6:13 am

Thank’s a lot!

This sample is awesome!

I used with Mime to send attachments in the mail.

12 Kiran S 05.27.07 at 12:36 pm

Hi,
I am not that good with php..its working when done stand alone.. i customized the code given by u to fit my text fields.. but didn’t work.. cud you give me some tips so that i can make it fit for my site

Kiran S

13 MANOJ 06.28.07 at 9:02 am

Hello,
I’ve been trying to send emails using the given php code in file named contact.php
Its showing error

Parse error: syntax error, unexpected ‘@’ in /home/paragpap/public_html/contact.php on line 5

What do I need to configure on my linux server to get it to work?

Please help…

Thanks

14 mazen 03.25.08 at 7:23 pm

Hi
any download zip file ?
Thanks

15 ehmeidan 04.16.08 at 10:10 am

thanks for this thing

16 Uma Mahesh 06.10.08 at 2:56 pm

i downloaded Mail package that contain a folder with Mail.php, Mail/*.php.
the code testmail.php was in the folder of Mail.php and when i execute it is asking for PEAR.php
i could not finid it.
Plz tell me how to install Pear on the server to
echo_mahesh@yahoo.co.in

17 Jake 06.13.08 at 10:51 am

can i check with you guys,
i have a sever currently installed with Apache,

i written a script in php to send emails out.
what do i need to install other than:
PHP5 and SMTP mail server?

18 Vikrant 07.15.08 at 12:16 pm

this code work for me, but I am not able to send attachment with mail. can anyone help me?

19 Uma Mahesh 07.15.08 at 1:59 pm

@vikrant
plz tell me how did u do it?

20 CrazyGuy 07.18.08 at 8:02 am

.scroll {font-weight:bold; font-size:36; text-align: center; font-family: Verdana,

Courier, Courier New;}

// globals
var initialx, initialy, scrolltext;
var frame = 0, frame2 = 0.5;
var amplitude1 = 50, amplitude2 = 30;
var offset = 0.2, speed = 0.2, speed2 = 0.35;
var offset2 = 0.6;
var scrollspeed = 6;
var charwidth = 30;

var twopi = Math.PI * 2;
var chracters, position, numvisible, nextchar, firstchar;
var skipsteps = 1;
var delaytimer = 0;
var interval;

// function to create sine scroller
function sinescroll (x, y, value, number_of_chars)
{
// setup globals
scrolltext = new String(value);
initialx = x;
initialy = y;
numvisible = number_of_chars;
nextchar = numvisible;
firstchar = 0;

// create fixed-size arrays of characters and positions
characters = new Array(numvisible);
position = initialx;

// write DIVs to hold characters
for (var i = 0; i < numvisible; i++)
{
document.write(”,
scrolltext.charAt(i), ”);
}
}

// animation function
function step ()
{
// increment counters
frame += speed;
frame2 += speed2;

// delay timer
if (delaytimer > 0)
{
delaytimer–;
}
else
{
// update position
position -= scrollspeed;
}

// check for ‘offscreen’
if (position < (initialx – charwidth))
{
while (scrolltext.charAt(nextchar) == ‘|’)
{
delaytimer += 90;
nextchar++;
}

// set nextchar into characters array
characters[firstchar].innerHTML = ” +

scrolltext.charAt(nextchar) + ”;

// update nextchar
nextchar++;

// check for wrap-around
if (nextchar >= scrolltext.length)
{
nextchar = 0;
}

// change position and counters by offset
position += charwidth;
frame += offset;
frame2 += offset2;

// update firstchar
firstchar++;

if (firstchar >= numvisible)
{
firstchar = 0;
}
}

// wrap-around counters
if (frame > twopi) frame -= twopi;
if (frame2 > twopi) frame2 -= twopi;

// set up loop variables
var angle = frame;
var angle2 = frame2;
var pos = position;

// update the html
for (var i=firstchar; i < numvisible; i++)
{
characters[i].style.left = pos;
characters[i].style.top = initialy + amplitude1 * Math.sin(angle) +

amplitude2 * Math.sin(angle2);
angle += offset;
angle2 += offset2;
pos += charwidth;
}

for (var i=0; i < firstchar; i++)
{
characters[i].style.left = pos;
characters[i].style.top = initialy + amplitude1 * Math.sin(angle) +

amplitude2 * Math.sin(angle2);
angle += offset;
angle2 += offset2;
pos += charwidth;
}
}

// start the animation
function start ()
{
if (!document.all)
return
// get all of the DIV tags into an array (IE only?)
characters = document.all.item(‘character’);

// setup timeout to call this function again
interval = window.setInterval(“step();”, 20);
}

// stop the animation
function stop ()
{
if (!document.all)
return
if (interval)
clearInterval(interval);
}

window.onload=start
window.onunload=stop

// create the scroller
if (document.all)
sinescroll(30, 100, “HI I Need to send more than one message field how can i do pls give me a solution Thanks. “, 15);

21 CrazyGuy 07.18.08 at 8:03 am

HI I Need to send more than one message field how can i do pls give me a solution Thanks.

22 peji 07.20.08 at 6:30 am

how can run without Mail.php?

23 Vikrant 07.24.08 at 11:24 am

hi Uma Mahesh,
u required xamplate which give u php and mysql, you also find mail.php file in it. just include it in this code.

24 Nuno 09.06.08 at 8:37 pm

Hi i tryed the code but it just give me this as answer in my browser:

send($recipients, $headers, $mailmsg)

Can anyone help me figure out what is the problem?

N

25 Digital Lynx 10.01.08 at 9:02 am

You could do all of that, but it’s pretty easy to do the above with the mMail library found here:

http://www.virtualthinking.com/loadhtml.php?where=scripts&what=art_show.php&db_target=00000000023

26 Joseph McLaughlin 10.24.08 at 8:39 pm

Hi,
When I run the php file in the browser I just get a blank page (also View Source is a blank page) no messages. I places an echo ‘Done” ; as the last statement and that doesn’t print.

Any thoughts anyone?

27 vivek 10.24.08 at 8:47 pm

Joseph,

Run php -i script.php to see error from the shell prompt.

28 Joseph McLaughlin 10.26.08 at 2:27 pm

vivek,

When I run “php -i smtp_test.php” from the terminal command prompt it returns 438 lines of definitions of properties, variables, etc., but I am unable to locate anything that appear to be errors.

29 vivek 10.26.08 at 2:50 pm

Joseph,

Opps, -i will return phpinfo(); it should be:
php script.php

30 Joseph McLaughlin 10.26.08 at 4:43 pm

vivek,

That works. It was a path issue on include(“/usr/share/pear/Mail.php”). When I moved smtp_test.php into the /usr/share/pear/ directory it sent the email, but that won’t work for me as my email scripts are in /var/www/vhosts//httpdocs/mailer/. Can I copy the PEAR PHP files into my mailer directory?

31 khalid 12.12.08 at 10:29 am

help me. :S

not working at my end.

32 Julius 12.26.08 at 3:12 am

Hello I found this code helpful but it works stand alone, How can I use it if I want to get all the data (name, email and message of the sender ) from a form in a html file or a contact form in SWF.
thanks

Julius

33 Ace 01.14.09 at 8:42 am

not sure I follow

34 Ruben Zevallos Jr. 01.25.09 at 12:52 pm

Hi, I’m looking for a 100% PHP sample… thanks for your post

35 sandhiya 01.29.09 at 8:08 am

Please tell me how i set mailmsg in html format in $mail_object->send($recipients, $headers, $mailmsg);

36 andres navarro 04.15.09 at 10:55 pm

Do you know how can i send an html mail using pear ?

37 articles submit 05.06.09 at 12:09 am

I got error : Fatal error: Undefined class name ‘mail’ line no 15 : $mail_object =& Mail::factory(“smtp”, $smtpinfo); how to fix this

38 Robbie Smith 05.14.09 at 4:05 am

Any reason why I’m getting this error:
Failed to connect to mail.capcontrollers.com:25 [SMTP: Failed to connect socket: No route to host (code: -1, response: )]

39 Caspar 07.14.09 at 1:11 pm

I get this error whenever trying to use the mail function on my WAMP server:

“Warning: mail() [function.mail]: Failed to connect to mailserver at “localhost” port 25, verify your “SMTP” and “smtp_port” setting in php.ini or use ini_set() in C:\Program Files\wamp\www\register.php on line 61″

What do I need to do?

Thanks alot.

40 Caspar 07.14.09 at 1:27 pm

Don’t worry – sorted it.

41 derek 09.03.09 at 10:45 am

i am getting this error
Warning: mail() [function.mail]: Failed to connect to mailserver at “localhost” port 25, verify your “SMTP” and “smtp_port” setting in php.ini or use ini_set()

can someone guide me so that i can use the mail() successfully

42 ashim 09.04.09 at 5:03 am

hey derek i have the same problem….. if u got it sorted out…… please let me know……

43 Thapar 11.11.09 at 9:06 pm

I have been using the following script to send a simple mail..it echoes “Good” as per the coding..but mail doesn’t appear in recipient’s inbox..!
My system configuration is Mac OSX 10.4.11..I have XAMPP installed on my Mac..and when I am trying to send mail..I have internet connectivity ( quite obvious ).
SMTP host is set to “localhost”..and port is set to 25.

$message = “Hi..\n Test message \n from site”;
$message = wordwrap($message, 70);
if(mail(‘thapar.dt@gmail.com’, ‘Mail Check’, $message)==true)
{
echo “Good”;
}
else echo “Not able to send mail”;
Do I need to install anything else..like any SMTP server or anything else..?
PS.- I have only XAMPP installed on my Mac for this purpose.

44 sangeeta 11.26.09 at 6:49 pm

somebody help me please

I am very frustrated as this scipt not sending the activation email to user.
i tried a lot.
this is script code from 1 to 105—————————————————————

is_valid) {
die ("Image Verification failed!. Go back and try again." .
"(reCAPTCHA said: " . $resp->error . ")");
}
$user_ip = $_SERVER['REMOTE_ADDR'];
$md5pass = md5($_POST['pwd']);
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$path = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');

$activ_code = rand(1000,9999);

$usr_email = mysql_real_escape_string($_POST['usr_email']);
$user_name = mysql_real_escape_string($_POST['user_name']);

$rs_duplicate = mysql_query("select count(*) as total from users where user_email='$usr_email' OR user_name='$user_name'") or die(mysql_error());
list($total) = mysql_fetch_row($rs_duplicate);

if ($total > 0)
{
$err = urlencode("ERROR: The username/email already exists. Please try again with different username and email.");
header("Location: register.php?msg=$err");
exit();
}

$sql_insert = "INSERT into `users`
(`full_name`,`user_email`,`pwd`,`address`,`tel`,`f ax`,`website`,`date`,`users_ip`,`activation_code`, `country`,`user_name`
)
VALUES
('$_POST[full_name]','$usr_email','$md5pass','$_POST[address]','$_POST[tel]','$_POST[fax]','$_POST[web]'
,now(),'$user_ip','$activ_code','$_POST[country]','$user_name'
)
";

mysql_query($sql_insert,$link) or die("Insertion Failed:" . mysql_error());
$user_id = mysql_insert_id($link);
$md5_id = md5($user_id);
mysql_query("update users set md5_id='$md5_id' where id='$user_id'");
// echo "Thank You We received your submission.";

$message =
"Thank you for registering with us. Here are your login details...\n

User ID: $user_name
Email: $usr_email \n
Passwd: $_POST[pwd] \n
Activation code: $activ_code \n

*****ACTIVATION LINK*****\n
http:$host$path/activate.php?user=$md5_id&activ_code=$activ_code

Thank You

Administrator
$host_upper
__________________________________________________ ____
THIS IS AN AUTOMATED RESPONSE.
***DO NOT RESPOND TO THIS EMAIL****
";

mail($usr_email, "Login Details", $message,
"From: \"Member Registration\" \r\n" .
"X-Mailer: PHP/" . phpversion());

header("Location: thankyou.php");
exit();

}

?>
————————————————————-
somebody please help me what to do.

Sangeeta

45 subhash 01.08.10 at 5:15 am

hi
please provide me full codding of mail function.
all:
How to configure;
changes configure;
html coding
thanx

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Previous post:

Next post: