[AWS] SES API를 통한 메일 발송 클래스
AWS에서 메일을 발송하는 방법에는 SMTP 설정을 통한 방법이 있고 다른 하나는 API를 이용한 방법이 있는데
여기에선 API를 이용한 방법에 대한 예 입니다.
보통 간단하게 조금 보낼때는 관계 없는데 많이 보내게 되면 AWS 비용이 비싸고 반송 메일에 따라 좋지 않으면 패널티도 받기 때문에 AWS 이용은 많이 안하는 편입니다.
대량메일 발송서비스만 전문으로 해주는곳을 이용하거나 직접 구축하여 발송을 하게 됩니다.
한달 몇 천건 정도면 이것 이용해도 됩니다.
require __DIR__ . '/../aws/aws-autoloader.php';
use Aws\Ses\SesClient;
use Aws\Exception\AwsException;
#
define('AWS_ACCESS_KEY_ID', 'aws에서 받은 키');
define('AWS_SECRET_ACCESS_KEY', 'aws 받은키');
define('AWS_REGION', 'ap-northeast-2');
/**
* AWS SES
*
* @package
*/
class AwsSES
{
private $client;
function __construct() {
$aAwsProfile = array(
'region' => AWS_REGION,
'version' =>'latest',
'credentials' => array(
'key' => AWS_ACCESS_KEY_ID,
'secret' => AWS_SECRET_ACCESS_KEY,
)
);
$sesClient = new SesClient($aAwsProfile);
$this->client = $sesClient;
}
public function sendEmai($senderName, $senderEmail, $aRecipientEmails, $subject, $htmlBody, $aFiles) {
$boundary = uniqid('boundary');
$charset = 'UTF-8';
// 메일 헤더 구성 - 인코딩을 하면 안된다. 자동으로 해주기 때문에 해주면 문제가 발생 한다.
$email_to = $aRecipientEmails[0];
$headers = "From: $senderName <$senderEmail>\r\n";
$headers .= "To: $email_to\r\n";
$headers .= "Subject: $subject\r\n";
$headers .= 'Date: ' . date('r') . "\r\n";
$headers .= "Return-Path: $senderEmail\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"{$boundary}\"\r\n";
$mailBody = "--{$boundary}\r\n";
$mailBody .= "Content-Type: text/html; charset={$charset}\r\n\r\n";
$mailBody .= $htmlBody . "\r\n";
foreach ($aFiles as $aFile) {
if ( !is_file($aFile['path']) ) continue;
$fileContent = file_get_contents($aFile['path']);
$fileName = basename($aFile['path']);
if (isset($aFile['name'])) $fileName = $aFile['name'];
$mailBody .= "--{$boundary}\r\n";
$mailBody .= "Content-Transfer-Encoding: base64\r\n";
$mailBody .= "Content-Type: {$aFile['type']}; name=\"{$fileName}\"\r\n";
$mailBody .= "Content-Disposition: attachment; filename=\"{$fileName}\"\r\n";
$mailBody .= "\r\n";
$mailBody .= chunk_split(base64_encode($fileContent)) . "\r\n";
}
$mailBody .= "--{$boundary}--\r\n";
try {
$result = $this->client->sendRawEmail([
'Source' => $senderEmail,
'Destinations' => $aRecipientEmails,
'RawMessage' => [ 'Data' => $headers . "\r\n" . $mailBody ]
]);
return $result;
}
catch (AwsException $e) {
return [
'Error' => $e->getAwsErrorMessage()
];
}
}
}
$senderEmail = 'tt1@test1.com';
$aRecipientEmails = array("tt2@test2.com");
$subject = '한글 Test Email - ' . date('Y-m-d H:i:s') ;
$htmlBody = '<h1> 한글</h1><p>attachment.</p> ' . date('Y-m-d H:i:s') ;
$aAttachments = [
['path' => '/root/pdf.pdf', 'type' => 'application/pdf'],
['path' => '/root/img.jpg', 'type' => 'image/jpeg', 'name' => '한글파일명.jpg']
];
$mailer = new AwsSES();
$oResult = $mailer->sendEmai('테스트', $senderEmail, $aRecipientEmails, $subject, $htmlBody, $aAttachments);
print_r($oResult);
* 참고자료
메일서버 설정 3종세트(DKIM, SPF, DMARC) > 리눅스서버
[AWS] SES SMTP 메일 발송하기 PHP Mailer
AWS SES 도메인 확인된 자격 증명 인증 방법(BIND 네임서버) > AWS.클라우드