Sample code for PHP SMTP authentication used script code Print

  • 0

Sample Code 1

<?php
//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
 
require 'PHPMailer-master/src/Exception.php';
require 'PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer-master/src/SMTP.php';
 
//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);
 
try {
    //Server settings
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
    $mail->isSMTP();                                            //Send using SMTP
    $mail->Host       = 'domainhostedwithus.com';                     //Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
    $mail->Username   = 'noreply@domainhostedwithus.com';                     //SMTP username
    $mail->Password   = 'PASSWORD-OF-EMAIL-ID';                               //SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
    $mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
 
    //Recipients
    $mail->setFrom('noreply@domainhostedwithus.com', 'Mailer');
    $mail->addAddress('noreply@domainhostedwithus.com', 'Name');     //Add a recipient email address and name 
 
 
 
    //Content
    $mail->isHTML(true);                                  //Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
 
    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
 
 
 

 

Sample Code 2

<?php
$mail = new EMail;
$mail->Username = 'test@DomainHostedWithUs.com';
$mail->Password = 'ThatEmailIDPasswordCreatedOnPanelWithUs';
$mail->setfrom("test@DomainHostedWithUs.com",""); // Name is optional
$mail->addto("test@DomainHostedWithUs.com",""); // Name is optional
$mail->addto("EmailIDWhereYouWantTogetEmailCopyTo"); // Add a receipient mail id
$mail->Subject = "Test php mail";
$mail->Message = "This is a test php auth mail";
//Optional stuff
$mail->ContentType = "text/html"; // Defaults to "text/plain; charset=iso-8859-1"
$mail->Headers['X-SomeHeader'] = 'abcde'; // Set some extra headers if required
$mail->ConnectTimeout = 30; // Socket connect timeout (sec)
$mail->ResponseTimeout = 8; // CMD response timeout (sec)
$success = $mail->Send();
class EMail
{
const newline = "\r\n";
private
$Server, $Port, $Localhost,
$skt;
public
$Username, $Password, $ConnectTimeout, $ResponseTimeout,
$Headers, $ContentType, $From, $To, $Cc, $Subject, $Message,
$Log;

function __construct()
{
$this->Server = "localhost";
$this->Port = 25;
$this->Localhost = "localhost";
$this->ConnectTimeout = 30;
$this->ResponseTimeout = 8;
$this->From = array();
$this->To = array();
$this->Cc = array();
$this->Log = array();
$this->Headers['MIME-Version'] = "1.0";
$this->Headers['Content-type'] = "text/plain; charset=iso-8859-1";
}
private function GetResponse()
{
stream_set_timeout($this->skt, $this->ResponseTimeout);
$response = '';
while (($line = fgets($this->skt, 515)) != false)
{
$response .= trim($line) . "\n";
if (substr($line,3,1)==' ') break;
}
return trim($response);
}
private function SendCMD($CMD)
{
fputs($this->skt, $CMD . self::newline);
return $this->GetResponse();
}
private function FmtAddr(&$addr)
{
if ($addr[1] == "") return $addr[0]; else return "\"{$addr[1]}\" <{$addr[0]}>";
}
private function FmtAddrList(&$addrs)
{
$list = "";
foreach ($addrs as $addr)
{
if ($list) $list .= ", ".self::newline."\t";
$list .= $this->FmtAddr($addr);
}
return $list;
}
function AddTo($addr,$name = "")
{
$this->To[] = array($addr,$name);
}
function AddCc($addr,$name = "")
{
$this->Cc[] = array($addr,$name);
}
function SetFrom($addr,$name = "")
{
$this->From = array($addr,$name);
}
function Send()
{
$newLine = self::newline;
//Connect to the host on the specified port
$this->skt = fsockopen($this->Server, $this->Port, $errno, $errstr, $this->ConnectTimeout);
if (empty($this->skt))
return false;
$this->Log['connection'] = $this->GetResponse();
//Say Hello to SMTP
$this->Log['helo'] = $this->SendCMD("EHLO {$this->Localhost}");
//Request Auth Login
$this->Log['auth'] = $this->SendCMD("AUTH LOGIN");
$this->Log['username'] = $this->SendCMD(base64_encode($this->Username));
$this->Log['password'] = $this->SendCMD(base64_encode($this->Password));
//Email From
$this->Log['mailfrom'] = $this->SendCMD("MAIL FROM:<{$this->From[0]}>");
//Email To
$i = 1;
foreach (array_merge($this->To,$this->Cc) as $addr)
$this->Log['rcptto'.$i++] = $this->SendCMD("RCPT TO:<{$addr[0]}>");
//The Email
$this->Log['data1'] = $this->SendCMD("DATA");
//Construct Headers
if (!empty($this->ContentType))
$this->Headers['Content-type'] = $this->ContentType;
$this->Headers['From'] = $this->FmtAddr($this->From);
$this->Headers['To'] = $this->FmtAddrList($this->To);
if (!empty($this->Cc))
$this->Headers['Cc'] = $this->FmtAddrList($this->Cc);
$this->Headers['Subject'] = $this->Subject;
$this->Headers['Date'] = date('r');
$headers = '';
foreach ($this->Headers as $key => $val)
$headers .= $key . ': ' . $val . self::newline;
$this->Log['data2'] = $this->SendCMD("{$headers}{$newLine}{$this->Message}{$newLine}.");
// Say Bye to SMTP
$this->Log['quit'] = $this->SendCMD("QUIT");
fclose($this->skt);
return substr($this->Log['data2'],0,3) == "250";
}
}
?>

 
 
 
Please Note:
- If you use the sample code, please make sure you create a separate file with the "above code only" and consult your developer to fill in the variables properly. If you simply copy and paste the code, it will not work, as the developer will need to customize the codes before putting them into use.
- You need to upload the code in a sample PHP file, with this code you just need to make sure that all your settings are working well, then after once working - your developer can take reference from this sample code and customize your website form or script accordingly.
- As a web host we are here for any specific server side error however any coding level support will not be possible.
- If you get any error in the logs related to PEAR packages, then contact our team can add .;.\includes;.\pear; to your PHP settings "includes" and check server-side PEAR packages.

Was this answer helpful?

« Back