일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- array
- 상태 코드
- laravel
- laravel 10
- pinia
- Key strech
- status code
- javascript
- http
- php
- 자바스크립트
- State Management
- smtp
- http header
- password
- typescript
- vue
- bubble sort
- Vue 3
- sort
- algorithm
- 알고리즘
- Pepper
- Date
- react
- salt
- 음성인식
- Web Speech API
- Today
- Total
Jin의 개발 블로그
Laravel 10.x Mail 보내는 방법 본문
Introduction
Laravel 10 에서 SMTP 서버를 이용해서 Mail을 보내는 방법에 설명드릴 것입니다. 사용버전은 Laravel 10 그리고 PHP 8.3 버전입니다. 구글 혹은 사내 구축 서버가 아닌 시중에 나와있는 SMTP 서버 이용해시 해당 서버의 드라이버를 설치해야하는 경우가 있습니다. 확인해주세요. 저 역시 사내 구축 서버를 이용했으나 예시에서는 Google SMTP를 이용할 것입니다.
.env
시작하기에 앞서 .env 설정을 변경하셔야합니다.
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=mygoogle@gmail.com
MAIL_PASSWORD=mygooglepassword
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=mygoogle@gmail.com
MAIL_FROM_NAME="${APP_NAME}"
위의 내용을 기본으로 설정이 됩니다. 이는 app/config.php 에서 확인 할 수 있습니다
Mailable
Mailable을 extend하고 있는 class를 생성해야합니다. 아래 명령어를 입력해주세요. 명령어 입력 후 "app/mail" Path에 "Invoice.php"이 생성된 걸 볼 수 있습니다.
php artisan make:mail InvoiceMail
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
class InvoiceMail extends Mailable
{
use Queueable, SerializesModels;
public $name;
public $attachemnts;
/**
* Create a new message instance.
*/
public function __construct($name, $attachemnts)
{
$this->name = $name;
$this->attachemnts = $attachemnts;
}
/**
* Get the message envelope.
*/
public function envelope(): Envelope
{
return new Envelope(
subject: 'Demo Mail',
);
}
/**
* Get the message content definition.
*/
public function content(): Content
{
return new Content(
view: 'emails.demoMail',
);
}
/**
* Get the attachments for the message.
*
* @return array
*/
public function attachments(): array
{
$result = array();
if ($this->attachemnts) {
foreach ($this->attachments as $attachment)
{
array_push($result, Attachment::fromPath(public_path('storage') . '/' . $attachment->name),);
}
}
return $result;
}
}
설명을 위해 위와 같이 변경했습니다.
envelope method
evnelope 메소드는 제목, 보내는 사람, 추가적으로 받을 사람을 추가 혹은 변경 할 때 사용합니다. Envelope class를 return 받습니다.
Property
from | 보내는 사람 설정. 기본적으로 config의 내용을 사용합니다. |
replyTo | 추가적으로 받는 사람 설정. 여러명을 설정 할 수 있습니다. |
subject | 제목 설정. 기본적으로 config의 내용을 사용합니다. |
tags | 태그를 추가합니다. Array 형태로 여러 개를 받을 수 있습니다. |
metadata | 메타 data를 추가합니다. Array 형태로 여러 개를 받을 수 있습니다. |
사용 예시
return new Envelope(
from: new Address('abc@example.com', 'Xyz'),
replyTo: [
new Address('xyz@example.com', 'Xyz'),
],
subject: 'Invoice for #123123',
tags: ['invoice'],
metadata: [
'invoiceId' => $this->invoice->id,
],
);
from 과 replyTo array의 element로는 Address class가 들어가야합니다.
subjects, tags, metadata는 필수 paramter가 아니기 때문에 없어도 상관없습니다.
global replyTo
'reply_to' => ['address' => 'example@example.com', 'name' => 'App Name'],
`config/email.php` 내의 config 세팅을 변경하여 모든 이메일 설정에 기본적으로 추가할 수 있습니다.
content method
content 메소드는 이메일을 Template을 변경 할 때 사용합니다. Content class를 return 받습니다.
사용예시
public function content(): Content
{
return new Content(
markdown: 'emails.invoice',
with: [
'today' => date('Y/m/d')
]
);
}
Property
view | 해당 path의 blade template을 html으로 가져옵니다. |
markdown | 해당 path의 blade template을 markdown으로 가져옵니다. |
with | blade template에서 class 위에 적은 변수들외의 추가적인 데이터를 사용 할 수 있게 합니다. |
View / Markdown
view와 markdown에는 어떤 blade template을 사용 할 것인지 정할 수 있습니다. 기본적으로 /resouces로 시작하기 때문에 resource 부분은 적지 않아도 됩니다. 추가적인 path "." 으로 구분 합니다. 파일명의 경우 .blade.php를 빼고 사용합니다.
위에 언급한 예시에 따르면 파일은 /resources/emails에 존재하며 파일명은 invoice.blade.php가 됩니다.
아래는 markdown 형태로 작성 invoice.blade.php 예제 입니다.
@component('mail::message')
Hello {{$name}}
Here is invoice
Thanks,<br>
{{ config('app.name') }}
{{ $today }}
@endcomponent
$name의 경우 변수로 지정된 데이터 이며, $today는 with 에 작성된 데이터 입니다.
추가적인 Markdown은 문법은 아래와 같습니다.
<x-mail::button :url="$url" color="success">
Button
</x-mail::button>
<x-mail::table>
| Col1 | Col2 | Price |
| ------------- |:-------------:| --------:|
| Row 1 | Centered | $10 |
| Row 2 | Right-Aligned | $20 |
</x-mail::table>
<x-mail::panel>
Panel content
</x-mail::panel>
위에서 부터 Button, table, panel 사용방법 입니다. Markdown에서 사용 하듯이 사용하면 됩니다.
attchments method
이메일에 첨부파일을 추가 할 때 사용합니다. array를 return 받으며, 안에는 Attachment class가 들어갑니다.
public function attachments(): array
{
return [
Attachment::fromPath('/path/to/file'),
];
}
Attahcment class
Attahcment class는 아래와 같은 method를 가지고 있습니다.
fromPath | Path에 있는 파일을 가져옵니다. Website link를 사용할 수도 있습니다. |
fromStorage | Larvel filesystem 내에 있는 파일을 가져옵니다. |
fromStorageDisk | 특정 disk에서 파일을 가져옵니다. |
추가적으로 파일명 및 mime type을 변경 할 수 있습니다.
return [
Attachment::fromPath('/path/to/file')
->as('super-invoice.pdf')
->withMime('application/pdf'),
];
as에는 파일명을 withMime type에는 mime type이 들어가야 합니다.
as 사용시 필수 적으로 extention, 확장자를 입력해주세요.
mime type 종류는 아래 링크에서 확인 할 수 있습니다.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
Common MIME types - HTTP | MDN
This topic lists the most common MIME types with corresponding document types, ordered by their common extensions.
developer.mozilla.org
header method
messageId, references(참조자) 및 text 의 내용을 변경 할 수 있습니다. header class를 return 받습니다.
간단하게만 사용할 때면 크게 건드실 부분은 없으실 겁니다.
public function headers()
{
return new Headers(
messageId: 'custom-message-id@example.com',
references: ['ref@example.com'],
text: [
'X-Custom-Header' => 'Custom Value',
],
);
}
예제는 공식 문서에서 가져왔습니다.
Controller
Controller에서 Mail의 to method를 활용해서 이메일을 보낼 수 있습니다. 아래는 예제입니다.
public function sendEmail(Request $request)
{
$request->validate([
'email' => 'required|string|email|max:255',
'name' => 'required|string|max:255'
]);
// send email
Mail::to($request->email)->send(new InvoiceMail(
$request->name,
[],
));
return response()->json([
'message' => 'Successfully sent',
]);
}
to 메소드에는 보내고자하는 email을 추가해주시면 됩니다.
send 메소드 안에는 Mailable을 extend 하고 있는 class가 들어가야합니다. 예시에서는 parameter가 있었기 때문에 추가해주었습니다.
참조자 추가
header 혹은 envelope를 변경하여 사용 할 수 있지만, 컨트롤 별로 따로 만들 수 있습니다.
Mail::to($request->email)
->cc($moreUsers)
->bcc($evenMoreUsers)
->send(new InvoiceMail(
$request->name,
[],
));
cc, bcc를 이용하여 이를 구현할 수 있습니다.
대량의 이메일 보내기
대량의 이메일을 보낼시 서버에 과부하를 이를 킬 수 있습니다. Laravel은 queue에 담아서 이를 쉽게 해결 할 수 있게 하였습니다.
Mail::to($request->user())
->queue(new InvoiceMail(
$request->name,
[],
));
send 대신 queue를 사용하여 보낼 수 있습니다.
항상 queue 상태로 보낼려면은
class InvoiceMail extends Mailable implements ShouldQueue
{
//
}
ShouldQueue를 implement하면 항상 queue 상태로 만들 수 있습니다.
Reference
https://laravel.com/docs/10.x/mail
Laravel - The PHP Framework For Web Artisans
Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.
laravel.com