언어/PHP

PHPMailer에서 gmail api로 메일 발송하기(XOAUTH2 인증)

greathuman 2022. 6. 9. 14:35

2022년 5월 31일부로 gmail의  보안 수준이 낮은 앱의 액세스 활성화 기능이 종료되었다.

 

해당 서비스가 종료되면서 phpmailer 5.2 버전으로 gmail smtp로 이메일을 발송하는 기능들이 다 막혀버렸다.

 

구글의 보안 정책에 따라 gmail api를 통해서 메일을 발송하려면 OAuth 2.0을 통해서 토큰을 부여받고

 

XOAUTH2 인증으로 메일을 발송해야한다.

 

XOAUTH2인증은 phpmailer 5.2에서 지원하지 않으므로 phpmailer 6.6을 설치해서 진행했다.

 


컴포저를 사용해 phpmailer 패키지 최신버전 설치

composer require phpmailer/phpmailer


google OAuth2.0을 사용하기 위해서.league/oauth2-google 패키지도 설치한다.

composer require league/oauth2-google

 

https://github.com/PHPMailer/PHPMailer/wiki/Using-Gmail-with-XOAUTH2

 

GitHub - PHPMailer/PHPMailer: The classic email sending library for PHP

The classic email sending library for PHP. Contribute to PHPMailer/PHPMailer development by creating an account on GitHub.

github.com

.패키지 설치 후 위의 방법대로 구글 웹어플리케이션을 만들어서 

clientId와 clientSecret 값을 가져온다.

 

get_oauth_token.php 파일에 생성된 정보를 채우고 실행시키면  Refresh Token 값을 리턴 받을 수 있다.

 

생성된 토큰을 가지고 메일을 발송하면 끝

 

 

 

<?php

/**
 * This example shows how to send via Google's Gmail servers using XOAUTH2 authentication
 * using the league/oauth2-client to provide the OAuth2 token.
 * To use a different OAuth2 library create a wrapper class that implements OAuthTokenProvider and
 * pass that wrapper class to PHPMailer::setOAuth().
 */

//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\OAuth;
//Alias the League Google OAuth2 provider class
use League\OAuth2\Client\Provider\Google;

//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');

//Load dependencies from composer
//If this causes an error, run 'composer install'
require '../vendor/autoload.php';

//Create a new PHPMailer instance
$mail = new PHPMailer();

//Tell PHPMailer to use SMTP
$mail->isSMTP();

//Enable SMTP debugging
//SMTP::DEBUG_OFF = off (for production use)
//SMTP::DEBUG_CLIENT = client messages
//SMTP::DEBUG_SERVER = client and server messages
$mail->SMTPDebug = SMTP::DEBUG_SERVER;

//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';

//Set the SMTP port number:
// - 465 for SMTP with implicit TLS, a.k.a. RFC8314 SMTPS or
// - 587 for SMTP+STARTTLS
$mail->Port = 465;

//Set the encryption mechanism to use:
// - SMTPS (implicit TLS on port 465) or
// - STARTTLS (explicit TLS on port 587)
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;

//Whether to use SMTP authentication
$mail->SMTPAuth = true;

//Set AuthType to use XOAUTH2
$mail->AuthType = 'XOAUTH2';

//Start Option 1: Use league/oauth2-client as OAuth2 token provider
//Fill in authentication details here
//Either the gmail account owner, or the user that gave consent
$email = 'someone@gmail.com'; //구글계정명이 아닌 발송하려는 gmail 메일주소를 입력해야한다.
$clientId = '';
$clientSecret = '';

//Obtained by configuring and running get_oauth_token.php
//after setting up an app in Google Developer Console.
$refreshToken = '';

//Create a new OAuth2 provider instance
$provider = new Google(
    [
        'clientId' => $clientId,
        'clientSecret' => $clientSecret,
    ]
);

//Pass the OAuth provider instance to PHPMailer
$mail->setOAuth(
    new OAuth(
        [
            'provider' => $provider,
            'clientId' => $clientId,
            'clientSecret' => $clientSecret,
            'refreshToken' => $refreshToken,
            'userName' => $email,
        ]
    )
);
//End Option 1

//Option 2: Another OAuth library as OAuth2 token provider
//Set up the other oauth library as per its documentation
//Then create the wrapper class that implementations OAuthTokenProvider
$oauthTokenProvider = new MyOAuthTokenProvider(/* Email, ClientId, ClientSecret, etc. */);

//Pass the implementation of OAuthTokenProvider to PHPMailer
$mail->setOAuth($oauthTokenProvider);
//End Option 2

//Set who the message is to be sent from
//For gmail, this generally needs to be the same as the user you logged in as
$mail->setFrom($email, 'First Last');

//Set who the message is to be sent to
$mail->addAddress('someone@gmail.com', 'John Doe');

//Set the subject line
$mail->Subject = 'PHPMailer GMail XOAUTH2 SMTP test';

//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->CharSet = PHPMailer::CHARSET_UTF8;
$mail->msgHTML(file_get_contents('contentsutf8.html'), __DIR__);

//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';

//Attach an image file
$mail->addAttachment('images/phpmailer_mini.png');

//send the message, check for errors
if (!$mail->send()) {
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message sent!';
}
?>