Genel

PHP ile Mail Gönderme API

Merhaba arkadaşlar kısaca phpmailer kütüphanesini kullanarak basit http post isteği ile mail gönderimi yapan bir api servisi yazacağız.

Makale Başlıkları

Adım 1: PHPMailer Kütüphanesinin İndirilmesi

PHPMailer kütüphanesi, e-posta gönderme işlemini kolaylaştırmak için kullanabileceğiniz bir PHP kütüphanesidir. Öncelikle, PHPMailer kütüphanesini indirin ve projenizin klasörüne ekleyin. İndirmek için buraya tıklayabilirsiniz.

Adım 2: api.php Dosyasının Hazırlanması

E-posta gönderimi yapacağınız api.php dosyasını hazırlıyoruz.

<?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\SMTP;
 use PHPMailer\PHPMailer\Exception;

 //Load Composer's autoloader
 require 'vendor/autoload.php';


 $allowSecret=['x1231x','vvas432'];

 if ($_POST) {

  if (in_array($_POST['data']['secret'], $allowSecret)) {
  

   //Create an instance; passing `true` enables exceptions
   $mail = new PHPMailer(true);

   try {
       //Server settings
       $mail->SMTPDebug = 0;                      //Enable verbose debug output
       $mail->isSMTP();                                            //Send using SMTP
       $mail->Host       = $_POST['data']['serverInfo']['hostname'];                     //Set the SMTP server to send through
       $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
       $mail->CharSet = "UTF-8";
       $mail->Username   = $_POST['data']['serverInfo']['username'];                     //SMTP username
       $mail->Password   = $_POST['data']['serverInfo']['password'];                               //SMTP password
       $mail->Port       = $_POST['data']['serverInfo']['port'];                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

       //Recipients
       $mail->setFrom($_POST['data']['serverInfo']['username']);


       foreach ($_POST['data']['address'] as $m) {
        $mail->addAddress($m);
       }

       $mail->addReplyTo($_POST['data']['reply']);


       foreach ($_POST['data']['cc'] as $c) {
        $mail->addCC($c);
       }


       foreach ($_POST['data']['bcc'] as $bc) {
        $mail->addBCC($bc);
       }


       //Content
       $mail->isHTML(true);                                  //Set email format to HTML
       $mail->Subject = $_POST['data']['subject'];
       $mail->Body    = $_POST['data']['body'];
       $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}";
   }
  }



 }else{

  echo "paramatre gönderilmedi, lütfen post ile bir parametre gönderin.";
 }


 ?>

Adım 3: mailgonder.php Dosyasının Hazırlanması

Bu dosya bizim api.php dosyasına yapacağımız http post request kodlarını içeriyor.

<?php 

$url = 'http://mailer.localhost/api.php';
$data = ['data' =>
 [

 'secret' => 'vvas432',
 'subject' => 'İletişim Formu',
 'body' => 'Bu bir test maildir lütfen yanıt vermeyin.',
 'serverInfo' => [
  'hostname' => 'mail.hostname.com',
  'username' => 'user@hostname.com',
  'password' => '&GPassxw',
  'port' => 587
 ],
 'address' => ['enesphp@gmail.com'], //maili alacak kişiler
 'reply' => 'info@test.com', //yanıt adresi
 'cc' => ['info@tetabilisim.com'],
 'bcc' => ['enes@tetabilisim.com']
 ] 

];


// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data)
    )
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) {  }

var_dump($result);

?>

mailgonder.php dosyasında kendi mail sunucu bilgilerinizi girmeyi unutmayın.

Videolu Anlatım 🙂

Admin

enesphp@gmail.com

Share
Published by
Admin

Recent Posts

Windows Ücretsiz VPN Nasıl Kurulur

Merhaba arkadaşlar hızlı bir şekilde windows ve diğer işletim sistemlerinde çalışan ve sizi engelli sitelerden…

3 ay ago

Google Ban Kontrolü PHP

Merhaba arkadaşlar, PHP kullanarak web sitemizin google'da banlanıp banlanmadığını kontrol edeceğiz. Bu işlemin mantığı google'a…

1 yıl ago

DNS Nedir

DNS, Domain Name System kelimelerinin kısaltmasıdır. İnternetin işleyişinde çok önemli bir rol oynayan DNS, internet…

1 yıl ago

Cpanel Cronjob Wget Log Dosyası Engelleme

Cron Job içinde dışarıya log dosyası oluşturtmadan wget kullanımı çok kolay, Bildiğiniz üzere her wget…

1 yıl ago

PHP ile SSL Checker Yapımı

PHP ile bir SSL sertifikasının geçerli olup olmadığını denetlemek için aşağıdaki kod kullanılabilirsiniz. <?php $url…

1 yıl ago

PHP array sıralamasını random yapma

PHP'de bir dizinin verilerini rastgele sıralamak için shuffle() fonksiyonu kullanılabilir: <?php $array = [1, 2,…

1 yıl ago