PHP – Google SMTP 서버 이용 이메일 전송

개발 이유 : 자체 SMTP 서버 세팅 이전에 급하게 필요한 이메일 전송기능 구현

이슈 : 보내는 사람 이름은 gmail 환경설정에서 인증을 한 후 변경이 가능하다. 인증을 하지 않으면 gmail 계정으로 계속 보내진다.

아주 베이직한 폼이니 필요한 경우 카피 후에 수정해서 사용하면 될 듯하다.

<!DOCTYPE html>
<html lang="ko">
  <head>
    <!-- charset 설정 -->
    <meta charset="UTF-8">
    <!-- ie 호환성보기 무시 -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- 모바일을 위한 viewport설정 -->
    <meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no">
    <title>Email Form</title>
    <style>
      .email_form input[type=text],
      .email_form select,
      .email_form textarea,
      .email_form input[type=email],
      .email_form input[type=tel] {
        width: 100%;
        padding: 12px;
        border: 1px solid #ccc;
        border-radius: 4px;
        box-sizing: border-box;
        margin-top: 6px;
        margin-bottom: 16px;
        resize: vertical;
      }
      
      .email_form>h3 {
        text-align: center;
      }
      
      .email_form textarea {
        height: 200px;
        resize: none;
      }
      
      .email_form input[type=submit] {
        background-color: #737373;
        color: white;
        padding: 12px 20px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        transition: 0.3s;
      }
      
      .email_form input[type=submit]:hover {
        background-color: #aaa;
      }
      
      .email_form {
        width: 90%;
        margin: 0 auto;
        margin-top: 50px;
        border-radius: 5px;
        padding: 20px;
      }
      
      .email_form>h3 {
        font-size: 30px;
        padding-bottom: 50px;
      }
 
    </style>
  </head>
 
  <body>
    <!-- 폼태그 -->
    <section class="email_form" id="email_form">
      <h3>Email Form</h3>
      <form action="index.php" method="post">
        <label for="from">From (required)</label>
        <input type="email" id="from" name="from" placeholder="from" autocomplete="on" required>
        <label for="to">To (required)</label>
        <input type="text" id="to" name="to" placeholder="to" autocomplete="on" required>
        
        <label for="cc">CC </label>
        <input type="text" id="cc" name="cc" placeholder="cc">
        
        <label for="subject">Subject </label>
        <input type="text" id="subject" name="subject" placeholder="subject" required>
        
        <label for="content">contents (required)</label>
        <textarea id="content" name="content" placeholder="content" required></textarea>
        <input type="submit" value="Send">
      </form>
    </section>
  </body>
 
</html>
<?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 $_SERVER["DOCUMENT_ROOT"] . '/PHPMailer-master/vendor/autoload.php';

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

$from = strip_tags(htmlspecialchars($_POST['from']));
$from_name = '{보내는사람 별칭}';
$rawTo = explode(',',strip_tags(htmlspecialchars($_POST['to'])));

$cc = strip_tags(htmlspecialchars($_POST['cc']));
echo $cc;
$subject = strip_tags(htmlspecialchars($_POST['subject']));
$contents = strip_tags(htmlspecialchars($_POST['content']));

// Cross-Site Scripting (XSS)을 방지하는 시큐어코딩
// strip_tags() -> 문자열에서 html과 php태그를 제거한다
// htmlspecialchars() -> 특수 문자를 HTML 엔터티로 변환
// 악의적인 특수문자 삽입에 대비하기 위함

// if(validate($from,$to,$subject,$contents) === false){
//   return;
// };

try {
    //Server settings
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      // Enable verbose debug output
    $mail->isSMTP();                                            // Send using SMTP
    $mail->Host       = 'smtp.gmail.com';                    // Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = '';                     // SMTP username
    $mail->Password   = '';                               // SMTP password
    $mail->SMTPSecure = "ssl";         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
    $mail->Port       = 465;                                    // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
    $mail->CharSet = 'UTF-8';

    //Recipients
    $mail->setFrom("{보내는사람 이메일 주소}", $from_name);
    //$mail->addAddress($to,"Valued Customer");     // Add a recipient
    //$mail->addReplyTo($to,'Reply to '.$from);
    if ($cc != null) {
      $cc = explode(',', $cc);
      for ($i = 0; $i < count($cc); $i++) {
          $mail->addCC($cc[$i]);
      }
  }
    

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = $subject;
    $mail->Body    = $contents;
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    foreach($rawTo as $to){
      $mail->ClearAddresses();
      $mail->addAddress($to,"Valued Customer"); 
      $mail->send();
    }
    echo 'Message has been sent successfully';
    
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}