Imagine that your web hosting provider don’t allow phpmail function and you have to use SMTP (Simple Mail Transfer Protocol)! So here is the solution : A simple contact form with SMTP and PHP that is easy to add on your website and yo configure.
On this simple tutorial, you will learn how to use a SMTP Contact form with some easy php code! and please if you find this useful, share it with your friends on social networks!
SMTP and PHP Contact Form
The script contain 3 files :
– contact.php
– Mysmtpconfig.php // SMTP Server Configuration
– smtpclass.php // SMTP Mail Sending Class
On Mysmtpconfig.php files you have to change SMTP server details :
<?php //Server Address $SmtpServer="127.0.0.1"; $SmtpPort="25"; //default $SmtpUser="username"; $SmtpPass="password"; ?>
The smtpclass.php file :
<?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; } } ?>
And our contact.php file :
<?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>