I've been learning more and more web development lately, watching videos here at laracasts, also following two official online courses in regards to PHP and one for AJAX, and I'm kinda stuck at the moment because I'm doing a lot of different things at the same time. So I decided to write a little PHP email class to keep myself busy which I want to use later for small web projects.
I'm just looking for different inputs and views from others on this simple class. I know there is no validation yet, and no spam protection and so on, but other than that, any input on what I can improve or are there any (major) errors with this class?
I'm not really looking for improvements such as the option to add an attachment or to change the priority, I'm just looking for insights on THIS class, as is.
Edit: I haven't commented anything since it's pretty straightforward and I will do that later when the class grows, but for displaying it here right now, it doesn't need any commenting imo. But yes, that is one thing I can improve indeed ;-)
class Email {
private $recipient = '[email protected]';
private $name;
private $email;
private $subject;
private $message;
private $headers = [];
public function __construct()
{
$this->addHeader('MIME-Version: 1.0');
$this->addHeader('X-Priority: 3');
$this->addHeader('X-MSMail-Priority: Normal');
$this->addHeader('X-Mailer: PHP/' . phpversion());
$this->addHeader('Content-Type: text/html; charset=iso-8859-1');
}
public function addHeader($header)
{
$this->headers[] = $header;
}
public function setSender($name, $email)
{
$this->name = $this->sanitizeData($name);
$this->email = $this->sanitizeData($email);
$this->addHeader('From: ' . $this->name . ' <' . $this->email . '>');
}
public function setSubject($subject)
{
$this->subject = $this->sanitizeData($subject);
}
public function setMessage($message)
{
$this->message = nl2br($this->sanitizeData($message));
}
public function sendMail()
{
mail($this->recipient, $this->subject, $this->message, implode("\r\n", $this->headers));
}
function sanitizeData($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
}
// Usage:
$mail = new Email;
$mail->setSender('My name', 'My email');
$mail->setSubject('My subject');
$mail->setMessage('My message');
$mail->sendMail();