PHP send mail SMTP authentification

this is a very complete php send mail script, with authentification ofcourse.
You can choose the smtp server, use your username and password, and can send a html email.

This script does not use php mail() function, it's all from scrach.





function authSendEmail($from, $namefrom, $to, $nameto, $subject, $message)
{

$smtpServer = "smtpout.europe.secureserver.net";
$port = "25";
$timeout = "30";
$username = "username@mailserver.com";
$password = "mypassword";
$localhost = "localhost"; //hosting server
$newLine = "\r\n";

$smtpConnect = fsockopen($smtpServer, $port, $errno, $errstr, $timeout);
$smtpResponse = fgets($smtpConnect, 515);
if(empty($smtpConnect))
{
$output = "Failed to connect: $smtpResponse";
return false;
} else {
$logArray['connection'] = "Connected: $smtpResponse";
}

//Request Auth Login

fputs($smtpConnect,"AUTH LOGIN" . $newLine);

$smtpResponse = fgets($smtpConnect, 515);


//Send username

fputs($smtpConnect, base64_encode($username) . $newLine);
$smtpResponse = fgets($smtpConnect, 515);

//Send password
fputs($smtpConnect, base64_encode($password) . $newLine);
$smtpResponse = fgets($smtpConnect, 515);

//Say Hello to SMTP
fputs($smtpConnect, "HELO $localhost" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);

//Email From
fputs($smtpConnect, "MAIL FROM: $from" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);

//Email To
fputs($smtpConnect, "RCPT TO: $to" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);

//The Email
fputs($smtpConnect, "DATA" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);

//Construct Headers
$headers = "MIME-Version: 1.0" . $newLine;
$headers .= "Content-type: text/html; charset=iso-8859-1" . $newLine;
//Add these two lines if you have any problem
//$headers .= "To: $nameto <$to>" . $newLine;

//$headers .= "From: $namefrom <$from>" . $newLine;


fputs($smtpConnect, "To: $nameto <$to>\nFrom: $namefrom <$from>\nSubject: $subject\n$headers\n\n$message\n.\n");
$smtpResponse = fgets($smtpConnect, 515);

// Say Bye to SMTP
fputs($smtpConnect, "QUIT" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);

return true;
}

?>

That's it, just copy this mail SMTP authentification function and change configuration variables values to your own (smtpserver, port, username, password, ...).

ob_start - save php output to a string - The PHP output buffering

I want to share this great php utility: the output buffering, it is sometimes very usefull. So what it does ?
The PHP output buffering will save all the server outputs ( html and php prints) to a string variable.

So to start buffering, use ob_start(); this will keep saved any output.
Then you use $variable = ob_get_clean(); to stop buffering, and copy the buffer content to the variable.

Here are few samples of the use of ob_start() and ob_get_clean()


<?php ob_start(); //Turn on output buffering ?>
Hello world, <a href="http://www.blogger.com/myotherpage.php">link</a>
<div class="style">Content</div>
<?php $var = ob_get_clean(); //copy current buffer contents into $message variable and delete current output buffer ?>


Now the content of the variable $var should be:

Hello word, <a href="http://www.blogger.com/myotherpage.php">link</a>
<div class="style">Content</div>


Another example (with php outputs buffered)

<?php ob_start(); ?>
Hello world, <?php echo "My Website"; ?>
Thank you.
<?php $var = ob_get_clean(); ?>


And this will be the content of $var:
Hello world, My Website
Thank you.

That's all !

PHP send HTML email, The complete php mail sending script

The last post by me was about a very easy way to send an email with php. But as it is simple, it will only send text email, not html.

If you want a complete mail sending script, that send in html, this is what you have to use:

<?php
//here the receiver of the email
$to = 'receiver@example.com';
//here 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: myemail@mysite.com\r\nReply-To: myemail@mysite.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/alternative; boundary=\"PHP-alt-".$random_hash."\"";
//define the body of the message.
$message ='
--PHP-alt-'.$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-alt-'.$random_hash.'--';

//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 script is with comments, to tell you what exactly each instruction does :)

So as you see, we added:
Content-Type: text/html; charset="iso-8859-1"
to the message body ($message), this way the mail client of the receiver will know that the email is in html.

There are also few other changements that are nor really very necessary like the boundary string, but it is better to use them :)

PHP mail() - send email with php

Sending email with php is very simple, few lines of code and it works.
You need to send email using php when you have a comment or contact us form, where your visitors contact you via a web page form, and you get the message to your email address, or when you have a signup / registration form and you want to send automatically a confirmation link or a welcome message to your new users.

This is how you send email using php:
<?php
$TO = "someone@something.com";
$h  = "From: me@mywebsite.com";
$message = "my message here";
mail($TO, $subject, $message, $h);
Header("Location: http://mysite.com/thankyou.html");
?>

That's it ! mail() function have 3 required parameters and one optional.
$To is the receiver email address, $subject is the subject and $message is the body of your message.
$h is optional, is the header you will send, it contains the sender email address ("FROM: me@mysite.com")

I will post next how to send a html email, and how to use SMTP Authentication which means how to choose the smtp server and use your username and password to use that server.

PHP Post data to url with curl

I know you will need sometimes to use a php code to send data (text) to an url using POST method, just like it was sent by a form.
So all you have to do now, is to copy this function and use it, you have to specify the url and the data to post and it goes !

<?php
function post_content($url,$nfields,$fields_string)  
{
    $ch = curl_init();  
    curl_setopt($ch, CURLOPT_URL, $url);  
    curl_setopt($ch,CURLOPT_POST,$nfields);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)');  
    ob_start();  
    curl_exec ($ch);  
    curl_close ($ch);  
    $string = ob_get_contents();  
    ob_end_clean();  
    return $string;      
}
?>

How this will work ? It's very easy:
1- First you need to know what url you want to post to using curl
2- You need to know what are the names of variables to post (textarea, checkbox..)
3- Their number
4-And their values

This is a quite easy exemple:
if the original form has these fields: textarea1, textarea2, and sends to "www.site.com/page.php", like this example:
<form name="form1" method="post" action="www.site.com/page.php">
  <textarea name="textarea1"></textarea>
  <textarea name="textarea2"></textarea>
</form>

You should use this function in this way:
post_content("http://www.site.com/page.html",2,"textarea1=value1&textarea2=value2")

$nfields=2 because you have two fields (textarea1 and textarea2) ,
$fields_sring = "textarea1=value1&textarea2=value2" because you want to post two variables ( fields values) value1 for the field textarea1 and value2 for the field textarea2, you have to write always "&" between each couple of fieldname-value.

What does this all mean, and for what ?
With this function you will be able to "assimilate" the use of the form and the submit button, and this mean you will be able to get the content of the page www.site.com/pahe.php without using the form, because php can't use a form :)

That's all !