Mengirim Email dengan Swiftmailer dan Slim

mail-1Untuk menambahkan fitur mengirim email pada aplikasi berbasis PHP, ada beberapa library yang dapat digunakan. Kalo saya pilihnya sih cari yang paling familiar dan banyak di innstall banyak orang. Dari beberapa yang ada, saya memilih swiftmailer, dikarenakan ini yang buat dari developernya symfony dan dipake di beberapa framework seperti symfony dan laravel.

Kali ini saya coba gabungkan dengan framework slim, kalo pake framework ini ga jauh beda dengan ga pake framework ko, dan bisa diubah sesuai dengan kebutuhan.

Instalasi

di composer.json ketik seperti ini

{
"require": {
"slim/slim": "^2.6",
"swiftmailer/swiftmailer": "@stable"
}
}

Kemudian install dengan perintah composer update.

Konfigurasi

Buat file index.php kemudian buatlah konfigurasi untuk slim dan swiftmailer (kali ini menggunakan smtp gmail, jadi sesuaikan username dan password gmail Anda

<?php require __DIR__ . '/vendor/autoload.php'; $app = new \Slim\Slim(); $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587,'tls') ->setUsername('[email protected]')
  ->setPassword('yourpassword')
  ;...

Form email

Berikutnya adalah route untuk menampilkan form email

....
$app->get('/form',function() use ($app) {
  $app->render('mail/form.tpl');
});
....

Kemudian untuk templatenya, buat folder templates, kemudian buat folder mail dan dalam folder mail buat file dengan nama form.tpl yang isinya sebagai berikut

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Contact Form</title>

    <!-- Bootstrap -->
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22https%3A%2F%2Foss.maxcdn.com%2Fhtml5shiv%2F3.7.2%2Fhtml5shiv.min.js%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
      <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22https%3A%2F%2Foss.maxcdn.com%2Frespond%2F1.4.2%2Frespond.min.js%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
    <![endif]-->
  </head>
  <body>

<div class="container">

<h2>Contact Form</h2>


<form class="form-horizontal" role="form" method="post" action="/sendEmail">

<div class="form-group">
              <label for="subject" class="col-sm-2 control-label">Subject</label>

<div class="col-sm-10">
                  <input type="text" class="form-control" id="subject" name="subject" placeholder="Subject Message" value="">
              </div>

          </div>


<div class="form-group">
              <label for="name" class="col-sm-2 control-label">Name</label>

<div class="col-sm-10">
                  <input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="">
              </div>

          </div>


<div class="form-group">
              <label for="email" class="col-sm-2 control-label">Email</label>

<div class="col-sm-10">
                  <input type="email" class="form-control" id="email" name="email" placeholder="[email protected]" value="">
              </div>

          </div>


<div class="form-group">
              <label for="message" class="col-sm-2 control-label">Message</label>

<div class="col-sm-10">
                  <textarea class="form-control" rows="4" name="message"></textarea>
              </div>

          </div>

          <<!-- div class="form-group">
              <label for="human" class="col-sm-2 control-label">2 + 3 = ?</label>

<div class="col-sm-10">
                  <input type="text" class="form-control" id="human" name="human" placeholder="Your Answer">
              </div>

          </div>

 -->

<div class="form-group">

<div class="col-sm-10 col-sm-offset-2">
                  <input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">
              </div>

          </div>


<div class="form-group">

<div class="col-sm-10 col-sm-offset-2">
                  <! Will be used to display an alert to the user>
              </div>

          </div>

      </form>

      
    </div>

 <!-- /container -->


    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22https%3A%2F%2Fcode.jquery.com%2Fjquery-2.1.4.min.js%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22https%3A%2F%2Fmaxcdn.bootstrapcdn.com%2Fbootstrap%2F3.3.5%2Fjs%2Fbootstrap.min.js%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
  </body>
</html>

Mengirim Email

Untuk emngirim email, pada index.php kita buat fungsi yang menjalankan mengirim email dari form tersebut seperti berikut

...
$app->post('/sendEmail',function() use ($app,$transport) {
  $mailer = Swift_Mailer::newInstance($transport);
  // Create a message
  $message = Swift_Message::newInstance($app->request->params('subject'))
    ->setFrom(array($app->request->params('email') => $app->request->params('name')))
    ->setTo(array('[email protected]'))
    ->setBody($app->request->params('message'))
    ;

  // Send the message
  if ($mailer->send($message))
  {
    echo "Sent\n";
  }
  else
  {
    echo "Failed\n";
  }
});

$app->run();

Selesai!! Mudah bukan, sekarang kita coba untuk mengisi form dan kirim. Jika berhasil, maka email akan terkirim ke alamat email Anda. Selamat mencoba