Kirim Email Attachment dengan PHP - Mari Belajar Coding

08 Mei 2019

Kirim Email Attachment dengan PHP


Kirim Email Attachment dengan PHP

Selamat datang di blog mari belajar coding. Pada tutorial kali ini kita akan belajar bagaimana cara mengirim email dengan attachment menggunakan PHP. Attachment merupakan sebuah berkas yang dikirim beserta isi pesan sebuah email. 

Kirim Email Attachment dengan PHP 

Download library phpmailer menggunakan composer. Buat folder mail di directory xampp/htdocs. kemudian buka cmd, arahkan kedalam directory xampp/htdocs/mail. Ketikkan kode berikut ini.
composer require phpmailer/phpmailer

Kirim Email Attachment dengan PHP

Baca juga: Cara Install dan Menggunakan Composer

Pastikan alamat email pengirim sudah di setting. Baca disini untuk merubah setting email sebagai pengirim. 
Konfigurasi Gmail di PHPMailer 

Buat file bernama latihan1.php di directory xampp/htdocs/mail. 
<?php
// 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';

// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = 0;                                       // Enable verbose debug output
    $mail->isSMTP();                                            // Set mailer to use SMTP
    $mail->Host       = 'smtp.gmail.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = 'emailpengirim';                       // SMTP username
    $mail->Password   = 'passwordemailpengirim';                               // SMTP password
    $mail->SMTPSecure = 'TLS';                                  // Enable TLS encryption, `ssl` also accepted
    $mail->Port       = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('emailpengirim', 'namapengirim');
    $mail->addAddress('emailpenerima', 'namepenerima');     // Add a recipient


    // Attachments
    $mail->addAttachment('phpmailer-min.png', 'image.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 <b>in bold!</b>';
    $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}";
}
Keterangan:
Ganti alamat email pengirim, nama pengirim, alamat email penerima, nama penerima dan nama file attachment.
Jalankan file melalui browser dengan mengetikkan localhost/mail/latihan1.php. Pastikan service apache xampp dalam keadaan start.

Mengirim email melalui form kirim email.
Kirim Email Attachment dengan PHP

Buat file bernama latihan2.php untuk membuat tampilan form kirim email. 
<!DOCTYPE html>
<html lang="en">
<head>
  <title>maribelajarcoding.com</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
  
</head>
<body>

<div class="container">
  <h2 align="center">Kirim Email Attachment dengan PHP</h2>
  <form class="form-horizontal" method="POST" enctype='multipart/form-data' id="FormEmail">
    <div class="form-group">
      <label class="control-label col-sm-2" for="email">Email Penerima:</label>
      <div class="col-sm-10">
        <input type="email" class="form-control" id="email" name="email">
      </div>
    </div>
    <div class="form-group">
      <label class="control-label col-sm-2" for="nama">Nama Penerima:</label>
      <div class="col-sm-10">
        <input type="text" class="form-control" id="nama" name="nama">
      </div>
    </div>
    <div class="form-group">
      <label class="control-label col-sm-2" for="nama">Subjek:</label>
      <div class="col-sm-10">
        <input type="text" class="form-control" id="subjek" name="subjek">
      </div>
    </div>
    <div class="form-group">
      <label class="control-label col-sm-2" for="pesan">Pesan:</label>
      <div class="col-sm-10">          
        <textarea class="form-control" rows="5" id="pesan" name="pesan"></textarea>
      </div>
    </div>
    <div class="form-group">
      <label class="control-label col-sm-2" for="Attachment">Attachment:</label>
      <div class="col-sm-10">          
        <input type="file" class="form-control" id="attachment" name="attachment">
      </div>
    </div>
    <div class="form-group">        
      <div class="col-sm-offset-2 col-sm-10">
        <button type="submit" name="submit" class="btn btn-primary">Kirim</button>
      </div>
    </div>
  </form>
  <h4 align="center"><a href="https://maribelajarcoding.com" target="_blank">maribelajarcoding.com</a></h4>
</div>
<script type="text/javascript">
    $("form").submit(function(e) {
         e.preventDefault();
          var form = $('#FormEmail')[0];

         var data = new FormData(form);
        $.ajax({
            url: 'send-mail.php',
            type: 'post',
            enctype: 'multipart/form-data',
            data: data,
            processData: false,
            contentType: false,
            cache: false,
            success: function(data) {
              alert(data);
              
            }
        });
    });
  </script>
</body>
</html>

Buat file send-mail.php untuk menerima data yang dikirim dari form latihan2.php menggunakan ajax submit.
<?php
// 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';

// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

$email_penerima=$_POST['email'];
$nama_penerima=$_POST['nama'];
$pesan=$_POST['pesan'];
$subjek=$_POST['subjek'];
$file_attachments=$_FILES['attachment']['tmp_name'];
$name_attachments=$_FILES['attachment']['name'];

try {
    //Server settings
    $mail->SMTPDebug = 0;                                       // Enable verbose debug output
    $mail->isSMTP();                                            // Set mailer to use SMTP
    $mail->Host       = 'smtp.gmail.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = 'emailpengirim';                     // SMTP username
    $mail->Password   = 'passwordemailpengirim';                               // SMTP password
    $mail->SMTPSecure = 'TLS';                                  // Enable TLS encryption, `ssl` also accepted
    $mail->Port       = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('emailpengirim', 'namapengirim');
    
    $mail->addAddress($email_penerima, $nama_penerima);     // Add a recipient


    // Attachments
    $mail->addAttachment($file_attachments, $name_attachments);    // Optional name

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = $subjek;
    $mail->Body    = $pesan;

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

Jalankan file latihan2.php  menggunakan browser dengan mengetikkan localhost/mail/latihan2.php. Pastikan services apache dalam keadaan start.

Source code:
mail attachment.rar


Related search:
Kirim email attachment dengan php
Kirim email menggunakan php

Related Posts

Load comments