The base PHP mail might not be good enough and certainly doesn’t have full suite of security. That’s why i suggest to use these popular Top 5 PHP Libraries for sending and parsing email.
1. SwiftMailer
Swift Mailer integrates into any web app written in PHP, offering a flexible and elegant object-oriented approach to sending emails with a multitude of feature. Swift Mailer is a for sending e-mails from PHP applications.Swift Mailer requires PHP 7.0 or higher (proc_* functions must be available).Swift Mailer does not work when used with function overloading as implemented by mbstring when mbstring.func_overload is set to 2.
Basic example
require_once '/path/to/vendor/autoload.php'; // Create the Transport $transport = (new Swift_SmtpTransport('smtp.example.org', 25)) ->setUsername('your username') ->setPassword('your password') ; // Create the Mailer using your created Transport $mailer = new Swift_Mailer($transport); // Create a message $message = (new Swift_Message('Wonderful Subject')) ->setFrom(['[email protected]' => 'John Doe']) ->setTo(['[email protected]', '[email protected]' => 'A name']) ->setBody('Here is the message itself') ; // Send the message $result = $mailer->send($message); |
2. PHPMailer
Many PHP developers utilize email in their code. The only PHP function that supports this is the mail() function. However, it does not provide any assistance for making use of popular features such as HTML-based emails and attachments. Formatting email correctly is surprisingly difficult. There are myriad overlapping RFCs, requiring tight adherence to horribly complicated formatting and encoding rules – the vast majority of code that you’ll find online that uses the mail() function directly is just plain wrong! Please don’t be tempted to do it yourself – if you don’t use PHPMailer, there are many other excellent libraries that you should look at before rolling your own – try SwiftMailer, Zend/Mail, eZcomponents etc.The PHP mail() function usually sends via a local mail server, typically fronted by a sendmail binary on Linux, BSD and OS X platforms, however, Windows usually doesn’t include a local mail server; PHPMailer’s integrated SMTP ,implementation allows email sending on Windows platforms without a local mail server.
A Simple Example
// 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\Exception;
//Load Composer's autoloader
require 'vendor/autoload.php';
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '[email protected]'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('[email protected]', 'Mailer');
$mail->addAddress('[email protected]', 'Joe User'); // Add a recipient
$mail->addAddress('[email protected]'); // Name is optional
$mail->addReplyTo('[email protected]', 'Information');
$mail->addCC('[email protected]');
$mail->addBCC('[email protected]');
//Attachments
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body in bold!';
$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;
}
|
3. Fetch
Fetch is a library for reading email and attachments, primarily using the POP and IMAP protocols.This is just a simple code to show how to access messages by using Fetch. It uses Fetch own autoload, but it can (and should be, if applicable) replaced with the one generated by composer.
use Fetch\Server; use Fetch\Message; $server = new Server('imap.example.com', 993); $server->setAuthentication('username', 'password'); /** @var Message[] $message */ $messages = $server->getMessages(); foreach ($messages as $message) { echo "Subject: {$message->getSubject()}", PHP_EOL; echo "Body: {$message->getMessageBody()}", PHP_EOL; } |
4. EmailReplyParser
EmailReplyParser is a PHP library for parsing plain text email content, based on GitHub’s email_reply_parser library written in Ruby.
Example
use EmailReplyParser\Parser\EmailParser;
$email = (new EmailParser())->parse($emailContent);
$fragment = current($email->getFragments());
$fragment->getContent();
$fragment->isSignature();
$fragment->isQuoted();
$fragment->isHidden();
$fragment->isEmpty();
?>
|
5. Stampie
Stampie have been moved to the “Flint” organization in order to get a better collaborative flow.Stampie is a simple API Wrapper for different email providers such as Postmark and SendGrid.
It is very easy to use and to integrate into your application as demonstrated below with a SendGrid mailer.
Example
// Stampie.phar does Autoloading through its Stup.php
require '/path/to/stampie.phar';
class Message extends \Stampie\Message
{
public function getFrom() { return '[email protected]'; }
public function getSubject() { return 'You are trying out Stampie'; }
public function getText() { return 'So what do you think about it?'; }
}
$adapter = new Stampie\Adapter\Buzz(new Buzz\Browser());
$mailer = new Stampie\Mailer\SendGrid($adapter, 'username:password');
// Returns Boolean true on success or throws an HttpException for error
// messages not recognized by SendGrid api or ApiException for known errors.
$mailer->send(new Message('[email protected]'));
|