9lessons programming blog
Loading Search
Monday, October 12, 2009

Send Mail using SMTP and PHP.

This post about "Sending Mail using SMTP and PHP". Now you can send emails with SMTP authentication using this script. Every mail needed server authentication, So you have to buy mail server. It's very useful you can implement this on your web projects.

Send Mail using SMTP and PHP
This tutorial contains three files.

- Index.php
- SMTPconfig.php // SMTP Server Cofiguration
- SMTPClass.php // SMTP Mail Sending Class


Download Script



SMTPconfig.php
You have to change SMTP server details.
<?php
//Server Address
$SmtpServer="127.0.0.1";
$SmtpPort="25"; //default
$SmtpUser="username";
$SmtpPass="password";
?>

SMTPclass.php
SMTP mail sending class.
<?php
class SMTPClient
{

function SMTPClient ($SmtpServer, $SmtpPort, $SmtpUser, $SmtpPass, $from, $to, $subject, $body)
{

$this->SmtpServer = $SmtpServer;
$this->SmtpUser = base64_encode ($SmtpUser);
$this->SmtpPass = base64_encode ($SmtpPass);
$this->from = $from;
$this->to = $to;
$this->subject = $subject;
$this->body = $body;

if ($SmtpPort == "")
{
$this->PortSMTP = 25;
}
else
{
$this->PortSMTP = $SmtpPort;
}
}

function SendMail ()
{
if ($SMTPIN = fsockopen ($this->SmtpServer, $this->PortSMTP))
{
fputs ($SMTPIN, "EHLO ".$HTTP_HOST."\r\n");
$talk["hello"] = fgets ( $SMTPIN, 1024 );
fputs($SMTPIN, "auth login\r\n");
$talk["res"]=fgets($SMTPIN,1024);
fputs($SMTPIN, $this->SmtpUser."\r\n");
$talk["user"]=fgets($SMTPIN,1024);
fputs($SMTPIN, $this->SmtpPass."\r\n");
$talk["pass"]=fgets($SMTPIN,256);
fputs ($SMTPIN, "MAIL FROM: <".$this->from.">\r\n");
$talk["From"] = fgets ( $SMTPIN, 1024 );
fputs ($SMTPIN, "RCPT TO: <".$this->to.">\r\n");
$talk["To"] = fgets ($SMTPIN, 1024);
fputs($SMTPIN, "DATA\r\n");
$talk["data"]=fgets( $SMTPIN,1024 );
fputs($SMTPIN, "To: <".$this->to.">\r\nFrom: <".$this->from.">\r\nSubject:".$this->subject."\r\n\r\n\r\n".$this->body."\r\n.\r\n");
$talk["send"]=fgets($SMTPIN,256);
//CLOSE CONNECTION AND EXIT ...
fputs ($SMTPIN, "QUIT\r\n");
fclose($SMTPIN);
//
}
return $talk;
}
}
?>

index.php
<?php
include('SMTPconfig.php');
include('SMTPClass.php');
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$to = $_POST['to'];
$from = $_POST['from'];
$subject = $_POST['sub'];
$body = $_POST['message'];
$SMTPMail = new SMTPClient ($SmtpServer, $SmtpPort, $SmtpUser, $SmtpPass, $from, $to, $subject, $body);
$SMTPChat = $SMTPMail->SendMail();
}
?>
<form method="post" action="">
To:<input type="text" name="to" />
From :<input type='text' name="from" />
Subject :<input type='text' name="sub" />
Message :<textarea name="message"></textarea>
<input type="submit" value=" Send " />
</form>

Latest 20 Articles
Sponsored Links

Share this post

Comments
{ 42 comments }
Anonymous said...

Thanks. Very useful.

scvinodkumar said...

Nice coding...

Anonymous said...

a piece of great code, thanks.

by the way, is there method to default the coding of the email as unicode(UTF8)?

gustavo said...

how can i add cc: ???

beezy said...

does this work for gmail smtp servers?

Srinivas Tamada said...

@beezy

No

Anonymous said...

You need to use unsecure mail servers that use port 25. Check your IP for details (if you have an email account with them, look under SMTP configuration for Outlook, Thunderbird, etc)

Anonymous said...

does it work for aol smtp server?

Premasis said...

Notice: Undefined variable: HTTP_HOST in C:\wamp\www\1010\SMTPclass.php on line 30

Anonymous said...

Thanks,
I really search for this script form last 1 week & i fount this script work fine for me.
Thanks again.

Sayf said...

Thank you very much for this useful class, how can we use it to send HTML emails?


@gustavo

It's possible to add cc.

1- You need to change first you index.php:

You've got to add a new field called cc in your form. Then recover it to $cc from POST Array (within the other variables as $from, $to ...). Finally, you must add $cc between $to and $subject in the SMTPClient function call.

2- Then you go to change SMTPClass.php:

You must add $cc to SMTPClient function definition the same way you did in the function call. THen add a new variable called $this->cc where you put the actual $cc.

Duplicate the RCPT TO command using your new variable $this->cc and get the response in the $talk[...] array:

fputs ($SMTPIN, "RCPT TO: <".$this->cc.">\r\n");
$talk["Cc"] = fgets ($SMTPIN, 1024);

Finally, put your variable on the mail header, by adding the following line right after its "To:" similar line under DATA command:
Cc: <".$this->cc.">\r\n

The final DATA command is:

fputs($SMTPIN, "DATA\r\n");
$talk["data"]=fgets( $SMTPIN,1024 );
fputs($SMTPIN, "To: <".$this->to.">\r\nCc: <".$this->cc.">\r\nFrom: <".$this->from.">\r\nSubject:".$this->subject."\r\n\r\n\r\n".$this->body."\r\n.\r\n");
$talk["send"]=fgets($SMTPIN,256);

That's it! You can do it the same way with BCc too...

Anonymous said...

i'm getting this error:
Notice: Undefined variable: HTTP_HOST in /var/www/vhosts/cutrin.lt/httpdocs/evelita/mailtest/SMTPClass.php on line 30

Anonymous said...

Thanks youuuuuuuuuuu.....

Anonymous said...

this not support html mail

alhakimi said...

problem when I send subject in arabic
How i solve it?

narasimha. said...

Thankq very Much.
God bless you

Anonymous said...

SMTPClass.php is not SMTPclass.php
Your script and include files names do not match,

Md. Ziaul said...

Warning: fsockopen() [function.fsockopen]: unable to connect to smtp.gmail.com:25 (A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. ) in D:\xampp\htdocs\NetBill Manager\admin\SMTPClass.php on line 28

Fatal error: Maximum execution time of 60 seconds exceeded in D:\xampp\htdocs\NetBill Manager\admin\SMTPClass.php on line 28

Anonymous said...

please help me to include headers
Ex: $headers = "Content-Transfer-Encoding: 8bit\r\n";
$headers .= 'Content-Type: text/html; charset="iso-8859-1"'."\r\n";

คอนโด said...

Thanks so much.

Anonymous said...

Notice: Undefined variable: HTTP_HOST in .../SMTPclass.php on line 30

Anonymous said...

Warning: fsockopen() [function.fsockopen]: php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\wamp\www\SMTPclass.php on line 31

Warning: fsockopen() [function.fsockopen]: unable to connect to 192.168.1.3 :25 (php_network_getaddresses: getaddrinfo failed: No such host is known. ) in C:\wamp\www\SMTPclass.php on line 31

Anonymous said...

i copied the three php programs and wen i try to run the index.php file it in d wamp server,
its gives d following error:
Warning: fsockopen() [function.fsockopen]: php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\wamp\www\SMTPclass.php on line 31

Warning: fsockopen() [function.fsockopen]: unable to connect to 192.168.1.3 :25 (php_network_getaddresses: getaddrinfo failed: No such host is known. ) in C:\wamp\www\SMTPclass.php on line 31

//i hav no clue wts wrong....m a newbie....i hav been tryn dis for a while but widout success....

Smit Shah said...

Nice post..

You can set header by this:

fputs($SMTPIN, "To: <".$this->to.">\r\nFrom: <".$this->from.">\r\nSubject:".$this->subject."\r\n".$this->headers."\r\n\r\n".$this->body."\r\n.\r\n");

And pass the header in constructor as an argument and than set that like:
$this->headers = $headers;

And that's all !!!

Anonymous said...

Reza Said:
how can I send email to more than one person on one textbox ?

Anonymous said...

Thanks Srinivas for this nice post. I reformatted your SMTPClient class and added a header variable so one has the option to send HTML emails.


SmtpServer = $SmtpServer;
$this->SmtpUser = base64_encode ($SmtpUser);
$this->SmtpPass = base64_encode ($SmtpPass);
$this->from = $from;
$this->to = $to;
$this->subject = $subject;
$this->body = $body;
$this->newLine = "\r\n";

if ($SmtpPort == "") {
$this->PortSMTP = 25;
} else {
$this->PortSMTP = $SmtpPort;
}
}

function SendMail (){
if ($SMTPIN = fsockopen ($this->SmtpServer, $this->PortSMTP)) {
fputs ($SMTPIN, "EHLO ".$HTTP_HOST."\r\n");
$talk["hello"] = fgets ( $SMTPIN, 1024 );

fputs($SMTPIN, "auth login\r\n");
$talk["res"]=fgets($SMTPIN,1024);

fputs($SMTPIN, $this->SmtpUser."\r\n");
$talk["user"]=fgets($SMTPIN,1024);

fputs($SMTPIN, $this->SmtpPass."\r\n");
$talk["pass"]=fgets($SMTPIN,256);

fputs ($SMTPIN, "MAIL FROM: <".$this->from.">\r\n");
$talk["From"] = fgets ( $SMTPIN, 1024 );

fputs ($SMTPIN, "RCPT TO: <".$this->to.">\r\n");
$talk["To"] = fgets ($SMTPIN, 1024);

fputs ($SMTPIN, "RCPT TO: \r\n");
$talk["Bcc"] = fgets ($SMTPIN, 1024);

fputs($SMTPIN, "DATA\r\n");
$talk["data"]=fgets( $SMTPIN,1024 );

//Construct Headers
$headers = "MIME-Version: 1.0" . $this->newLine;
$headers .= "Content-type: text/html; charset=iso-8859-1" . $this->newLine;
$headers .= "From: <".$this->from.">". $this->newLine;
$headers .= "To: <".$this->to.">". $this->newLine;
$headers .= "Bcc: newLine;
$headers .= "Subject: ".$this->subject. $this->newLine;

fputs($SMTPIN, $headers."\r\n\r\n".$this->body."\r\n.\r\n");

$talk["send"]=fgets($SMTPIN,256);
//CLOSE CONNECTION AND EXIT ...
fputs ($SMTPIN, "QUIT\r\n");
fclose($SMTPIN);
//
}
return $talk;
}
}
?>

Anonymous said...

Anyone know a way to make this code work with Gmail? Dont you just need to allow SSL somehow and use port 465 or 587?

Actual Soft Solutions said...

Mails are going to Spam box. can you help me resolve it.

ali said...

I am getting this error please help me to solve


Undefined variable: HTTP_HOST in C:\wamp\www\smtp\SMTPclass.php on line 39

Zoinks! Graphics said...

Does this have any special server-end requirements to run? My host (DreamHost) is saying that SMTP like this requires PEAR and the fact that I can't get it to work seems to back that up. Not getting any errors like some users above, just no emails coming thru. Any thoughts?

Brad said...

heh.. I had this working last weekend.. I think my CPanel server either upgraded exim or something because this script is now sending out emails but when it hits the exim server im getting errors:
2011-09-10 08:17:13 H=area (localhost) [127.0.0.1] rejected MAIL notifications@email.tld: Authentication failed

Thoughts on that? I know its not the php issue, or is it? Running 5.3.8 of PHP

chansi said...

thnx for this class ,
but how can i get a confirmation message
if mail fails to b delivered then how can i get to know about that ??

Judhisthria Sahoo said...

Hi,

All..It is best code which help me very bad time...Thanks you all guys..and for your valuable posting..

I have seen one post is no pending for help..

Undefined variable: HTTP_HOST in C:\wamp\www\smtp\SMTPclass.php

Who are waiting for the above error code help..
plz see the bellow

----------
Please replace the "$HTTP_HOST" to "$this->SmtpServer".

Then enjoy the fun with you..

judhisthira sahoo
India

Anonymous said...

Thank you

it is excellent .

But how to set server inside config file to send Email to yahoo ?

Steven said...

Nice job,

this code worked beautifully for me to connect to godaddys smtp

YISHIyish said...

I have tried this and its working properly. Is it possible to add attachment when sending an email using smtp? Thanks. :)

Nafees Mansoor said...

nice script. but can u plz help me out on the attachment issue?

Anonymous said...

to solve problem of "Undefined variable: HTTP_HOST"
replace it with "getenv('MyHost')", it worked well with me...


and i am reallly grateful for this post..thank you soooo much (^_^)

Anonymous said...

regarding the SMTPconfig.php... ca we put mail.domain.com at $SmtpServer? something like this:


any help?

5e02b01c-21bf-11e1-ab39-000bcdca4d7a said...

The Bcc or Cc seem to work however the received email also shows who the Bcc/Cc is. For Bcc this is a problem b/c it's not BLIND. The following is what my hosting company said about this:

"It looks as your script is adding the BCC header of the message. at the wrong place. We would recommend that you check the configuration of the script that you are using to send the message. "

Anonymous said...

Thanks a lot. You are the man!

Anonymous said...

the line

$talk["hello"] = fgets ( $SMTPIN, 1024 );

Would be better as

$talk["hello"] = stream_get_line( $SMTPIN, 1024 );

as the server can return a multi line greeting which can still be returned in many of the following fget commands rather than getting what you would expect.

Post a Comment

Subscribe now!Recent Posts

Categories

Subscribe now!Popular Posts

People Says

@9lessons thank you for the great tutorials, we truly appreciate your contributions to the design community.

Smashing Magazine

Like Me

follow me
products

9lessons labs

9lessons clouds

Android application

Chrome Extension