오늘은 PHP서버를 이용하여 메일을 발송하는 방법을 알려드리려고 합니다.
PHP Mailer를 사용하였으며, 개발환경은 Laravel 5.6 Version 입니다.
굳이 Laravel을 사용하지 않으시더라도, Composer를 사용하고 계신다면 사용이 가능하기 때문에 걱정하실 필요는 없으 실 것 같습니다.
또한 메일을 발송할 메일 서버가 필요한데, 무료 메일서버는 gmail 을 사용해 주시는 편이 가장 간편한 것 같습니다.
1. php mailer 설치
https://github.com/PHPMailer/PHPMailer
composer require phpmailer/phpmailer
일단, 프로젝트에 들어가기 전에 위 명령어를 실행하여 php mailer를 설치해 줍니다.
2. 메일 발송 모델 작성
위 링크에서 A Simple Example 섹션을 확인해 주시면 소스코드를 상세히 보실 수 있는데요,
기본적으로 SMTP서버가 존재 해야 하니, 이점 유의해 주시고 소스코드를 봐주시면 될 것 같습니다.
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
// Load Composer's autoloader
require 'vendor/autoload.php';
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp1.example.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user@example.com'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('joe@example.net', 'Joe User'); // Add a recipient
$mail->addAddress('ellen@example.com'); // Name is optional
$mail->addReplyTo('info@example.com', 'Information');
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');
// Attachments
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$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}";
상세히 주석으로 파라미터들이 설명이 되어 있는데요, 부가적으로 설명을 드리자면
SMTPDebug => 개발 이후에는 주석 처리 해 줍시다.
Host => SMTP서버 호스트를 입력해 주세요.
Username => SMTP 서버에서 메일을 발송할 주소를 입력해 주세요.
Password => Username 에서 적은 메일의 비밀번호를 입력해 주세요.
Port => SMTP 서버의 포트 번호를 입력해 주세요.
SetFrom => 메일을 받은 사용자에게, 어디에서 보냈는지 표기하는 부분입니다. (메일주소, 발송자명)
addFrom => 수신자 입니다.
addReplyTo, CC, BCC => 답장, 참조 등등 이므로, 일반적인 경우에는 주석 처리 해주세요.
addAttachment => 첨부파일입니다. (파일경로, 사용자에게 보여 줄 파일 명)
단, 웹경로는 지정이 되지 않으며, 메일을 보내는 서버 내에서 접근이 가능한 파일이어야 첨부가 됩니다.
Subject => 메일의 주소 입니다.
Body => 메일 본문입니다.
HTML 코드를 작성 할 수 있는데, CSS와 javascript 등도 직접 코딩 하여서 넣어 줄 수 있습니다만, 스크립트의 경우에는 보안상의 문제로 일부 제대로 작동하지 않을 수 있습니다.
CSS는 아래와 같은 방식으로 넣어 주셔야 작동합니다.
<div style='width:300px;'> </div>
send => 메일을 발송합니다. 이후, echo 'Message has been sent' 부분에서 메일 발송 이후 처리될 서버단을 개발해 주시면 되며,
catch 이후에는 메일 발송 실패시 처리된 서버단을 개발해 주시면 됩니다.
3. phpMailer 한글 설정
실제로 메일을 발송시, 보통 한글이 깨져서 발송되게 됩니다. 이럴땐 최상단에
$mail->CharSet = 'UTF-8';
위와 같이 해주시면 인코딩 문제가 해결 됩니다.
추가적으로 나의 Gmail을 이용하여 메일을 발송하고 싶으시다면,
https://support.google.com/mail/answer/7126229?hl=ko
를 확인해 주세요!
'PHP > PHP' 카테고리의 다른 글
Laravel - passport를 이용한 로그인 구현 (Oauth) (2) | 2022.05.03 |
---|---|
[Laravel] Laravel + Vue 연동 (0) | 2020.12.15 |
[Laravel] AWS S3 연동하기 및 파일 업로드 구현 (0) | 2019.12.11 |
PHP를 이용한 동영상 썸네일 추출 (2) | 2018.03.13 |
dompdf를 이용한 HTML -> PDF 변환 (0) | 2018.03.08 |