Tuesday, September 25, 2018

PHP Mail Using Object Oriented Programming (OOP)




The bellow object contains four private properties and three accessor methods and finally one more method to dispose of the email to recipients. So how we are going to use it our PHP code? Let's see Below: 

<?
//class.emailer.php
class emailer
{
private $sender;
private $recipients;
private $subject;
private $body;
function __construct($sender)
{
$this->sender = $sender;
$this->recipients = array();
}
public function addRecipients($recipient)
{
array_push($this->recipients, $recipient);
}
public function setSubject($subject)
{
$this->subject = $subject;
}
public function setBody($body)
{
$this->body = $body;
}
public function sendEmail()
{
foreach ($this->recipients as $recipient)
{
$result = mail($recipient, $this->subject, $this->body,
"From: {$this->sender}\r\n");
if ($result) echo "Mail successfully sent to
{$recipient}<br/>";
}
}

$emailerobject = new emailer ("maninchiev@yahoo.com");
$emailerobject->addRecipients("DAra@gmail.com");
$emailerobject->setSubject("Test Email");
$emailerobject->setBody("HI Manin, HOw are you");
$emailerobject->sendEmail();

?>
}