[AWS] SES API + PEAR MIME 라이브러리 활용하는 방법
AWS SES API를 활용하면서 PEAR 라이브러리 활용할 필요가 있을 때 사용하면 되지만 일반적으로는 사용할 필요는 없습니다.
하지만 필요한 분이 있을 수 있어 예전 소스중에 있어 올립니다.
1) PEAR 설치
사용하는 PHP 버전의 경로를 지정해서 설치 해야 한다.
wget https://pear.php.net/go-pear.phar
/usr/local/php82/bin/php go-pear.phar
/usr/local/php82/bin/php -r "include 'PEAR.php';"
2) MIME 라이브러리
압축을 푼 다음 폴더를 옮겨 사용해야 한다. 라이브러리에서 또다른 파일 include 하면서 경로 문제 때문에 그렇다.
wget https://pear.php.net/package/Mail_Mime/download
tar xvfz Mail_Mime-1.10.11.tgz
mv Mail_Mime-1.10.11/Mail/ ./
/usr/local/php82/bin/php -r "include 'Mail/mime.php';"
/**
* AWS SES API PEAR
*/
require __DIR__ . '/../aws/aws-autoloader.php';
use Aws\Ses\SesClient;
use Aws\Exception\AwsException;
include 'Mail/mime.php';
#
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=[] ) {
$email_sender = mb_encode_mimeheader($senderName, 'UTF-8', "Q") . " <" .$senderEmail. ">";
$email_to = $aRecipientEmails[0];
$aMailHeader = array(
'From' => $email_sender,
'To' => $email_to,
'Date' => date('r'),
'Subject' => $subject,
'Return-Path' => $senderEmail
);
// mail body
$aMailSet = [
'eol' => "\n",
'head_charset' => 'UTF-8',
'html_charset' => 'UTF-8',
'text_charset' => 'UTF-8'
];
$aMime = new Mail_mime($aMailSet);
$aMime->setHTMLBody($htmlBody);
foreach ($aFiles as $key => $aFile ) {
$mime_type = ($aFile['type']) ? $aFile['type']:'application/octet-stream';
$fileName = basename($aFile['path']);
if ( isset($aFile['name']) ) {
$fileName = mb_encode_mimeheader($aFile['name'], 'UTF-8', 'B', "\r\n");
}
$aMime->addAttachment($aFile['path'], $mime_type, $fileName);
}
$mailBody = $aMime->get();
$headers = $aMime->txtHeaders($aMailHeader);
$message = $headers . "\r\n" . $mailBody;
try {
$sesClient = $this->client;
$oResult = $sesClient->sendRawEmail([
'Source' => $senderEmail,
'Destinations' => $aRecipientEmails,
'RawMessage' => [ 'Data' => $message ]
]);
return $oResult;
}
catch (AwsException $e) {
return "Email not sent. 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);