Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mandrill app mailer driver integration #3

Merged
merged 6 commits into from
Jan 31, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
"name": "justcoded/form-handler",
"require": {
"vlucas/valitron": "^1.4",
"phpmailer/phpmailer": "^6.0"
"phpmailer/phpmailer": "^6.0",
"mandrill/mandrill": "1.0.*"
},
"autoload": {
"files": [
Expand Down
50 changes: 47 additions & 3 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions examples/form.php → examples/form2email-basic.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
] // according to Valitron doc.
];

// PhpMailer config.
$mailerConfig = [
'mailer' => MailHandler::USE_PHPMAILER, // (or USE_POSTMARKAPP, USE_MANDRILL)
'host' => 'smtp.gmail.com',
Expand Down
76 changes: 76 additions & 0 deletions examples/form2email-mandrill.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?php

// enable errors => debug mode.
ini_set('display_errors', 1);
error_reporting(E_ALL);

// init autoload.
require __DIR__ . '/../vendor/autoload.php';

use JustCoded\FormHandler\FileManager\FileManager;
use JustCoded\FormHandler\FormHandler;
use JustCoded\FormHandler\Handlers\MailHandler;
use JustCoded\FormHandler\DataObjects\MailMessage;

$validation = [
'fields' => [
'name' => ['required'],
'email' => ['required', 'email'],
'subject' => ['required'],
'message' => [
'required',
['lengthMin', 5]
],
'cv_file' => [
[
'required',
'message' => 'Please upload {field}',
],
[
'file',
['jpeg', 'jpg', 'png'], // types.
2000000, // size limit 2 MB.
'message' => '{field} should be up to 2MB and allows only file types jpeg, png.',
],
],
], // according to Valitron doc for mapFieldsRules.
'labels' => [
'name' => 'Name',
'email' => 'Email address'
] // according to Valitron doc.
];

// Mandrill config.
$mailerConfig = [
'mailer' => MailHandler::USE_MANDRILL, // (or USE_POSTMARKAPP, USE_MANDRILL)
'apiKey' => '_5mPSvb39BQqnA7G_dOaAA',
'attachmentsSizeLimit' => 8000000, // around 8MB.
];

$fileManager = new FileManager([
'uploadPath' => __DIR__ . '/attachments',
'uploadUrl' => 'http://MY-DOMAIN.COM/attachments',
]);

$message = [
'from' => ['[email protected]' => 'FROM NAME'],
'to' => ['[email protected]' => 'TO NAME'],
// 'cc' => ['email' => 'name'],
// 'bcc' => ['email' => 'name'],
'subject' => 'Contact request from {name}',
'bodyTemplate' => __DIR__ . '/template-html.php',
'altBodyTemplate' => __DIR__ . '/template-plain.php',
'attachments' => $fileManager->upload([
'cv_file', 'image_file'
])
];


$mailer = new MailHandler($mailerConfig, new MailMessage($message));
$formHandler = new FormHandler($validation, $mailer);

if ($formHandler->validate($_POST)) {
$formHandler->process();
}

echo json_encode($formHandler->response());
12 changes: 11 additions & 1 deletion examples/index.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<html>
<body>

<form action="form.php" method="post" enctype="multipart/form-data">
<form action="form2email-basic.php" method="post" enctype="multipart/form-data">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
Subject: <input type="text" name="subject"><br>
Expand All @@ -10,6 +10,16 @@
<p>File2:<input type="file" name="image_file"></p>
<input type="submit">
</form>
<hr>
<form action="form2email-mandrill.php" method="post" enctype="multipart/form-data">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
Subject: <input type="text" name="subject"><br>
Message: <textarea name="message"></textarea>
<p>File1:<input type="file" name="cv_file"></p>
<p>File2:<input type="file" name="image_file"></p>
<input type="submit">
</form>

</body>
</html>
10 changes: 10 additions & 0 deletions src/DataObjects/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,16 @@ public function getExtension()
return pathinfo($this->name, PATHINFO_EXTENSION);
}

/**
* Represent image in base64 encode format
*
* @return string
*/
public function getBase64()
{
return base64_encode(file_get_contents($this->uploadPath));
}

/**
* Magic method for template converting
*
Expand Down
12 changes: 8 additions & 4 deletions src/Mailer/MailerFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,22 @@
class MailerFactory
{
/**
* Creating Mailer
* Create mailer depends on the type config
*
* @param string $type Type mailer
* @param string $type Type of Mailer
* @param array $config Mailer config
*
* @return PHPMailer
* @return MandrillMailer|PHPMailer
*/
public static function create(string $type, array $config) {
public static function create(string $type, array $config)
{
switch ($type) {
case MailHandler::USE_PHPMAILER:
$mailer = new PHPMailer($config);
break;
case MailHandler::USE_MANDRILL:
$mailer = new MandrillMailer($config);
break;
default:
new \Exception("MailerFactory: unable to find mailer for type \"{$type}\"");
}
Expand Down
120 changes: 120 additions & 0 deletions src/Mailer/MandrillMailer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
<?php

namespace JustCoded\FormHandler\Mailer;

use JustCoded\FormHandler\DataObjects\DataObject;
use JustCoded\FormHandler\DataObjects\EmailAttachment;
use JustCoded\FormHandler\DataObjects\MailMessage;
use Mandrill;
use Mandrill_Error;

/**
* Class MandrillMailer
*
* @package JustCoded\FormHandler\Mailer
*/
class MandrillMailer extends DataObject implements MailerInterface
{
/**
* Attachments size limit
*
* @var int
*/
protected $attachmentsSizeLimit = 8000000;

/**
* User from user config
*
* @var string
*/
protected $user;

/**
* Password from user config
*
* @var string
*/
protected $apiKey;

/**
* List of errors
*
* @var array
*/
protected $errors = array();

/**
* Sending form
*
* @param MailMessage $message Mailer message
*
* @return array|bool
*/
public function send(MailMessage $message)
{
try {
$mandrill = new Mandrill($this->apiKey);

$mandrillMessage = array(
'html' => $message->getBody(),
'subject' => $message->getSubject(),
'from_email' => $message->getFrom()->getEmail(),
'from_name' => $message->getFrom()->getName(),
);

// Recipients.
$recipients = [
'to' => $message->getTo(),
'cc' => $message->getCc(),
'bcc' => $message->getBcc()
];

$to = [];
foreach ($recipients as $type => $emails) {
if (empty($emails)) continue;
foreach ($emails as $email) {
$to[] = [
'email' => $email->getEmail(),
'name' => $email->getName(),
'type' => $type
];
}
}

$mandrillMessage['to'] = $to;

// Attachments.
if (0 < $message->getAttachmentsSize() && $message->getAttachmentsSize() < $this->attachmentsSizeLimit
&& $attachments = $message->getAttachments()
) {
$attachmentsArray = [];
foreach ($attachments as $attachment) {
$attachmentsArray[] = [
'type' => $attachment->type,
'name' => $attachment->name,
'content' => $attachment->getBase64()
];
}

$mandrillMessage['attachments'] = $attachmentsArray;
}

$result = $mandrill->messages->send($mandrillMessage);

return $result;
} catch (Mandrill_Error $e) {
$this->errors[] = 'A mandrill error occurred: ' . get_class($e) . ' - ' . $e->getMessage();
return false;
}
}

/**
* Getting list of errors
*
* @return array
*/
public function getErrors()
{
return $this->errors;
}
}