larave9发送邮箱 代码
时间: 2023-06-01 08:05:43 浏览: 98
对于 Laravel 9 发送邮件的代码,您可以使用以下代码来实现:
首先,确保您已经在 Laravel 9 项目中安装了邮件发送支持,可以使用以下命令来安装:
```
composer require illuminate/mail:^9.0
```
然后,在 `.env` 配置中添加邮件发送的配置信息:
```
MAIL_MAILER=smtp
MAIL_HOST=your-smtp-host
MAIL_PORT=your-smtp-port
MAIL_USERNAME=your-smtp-username
MAIL_PASSWORD=your-smtp-password
MAIL_ENCRYPTION=your-smtp-encryption
MAIL_FROM_ADDRESS=your-from-email-address
MAIL_FROM_NAME="${APP_NAME}"
```
然后,在 `config/mail.php` 中配置邮件发送的默认选项:
```
'default' => env('MAIL_MAILER', 'smtp'),
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'host' => env('MAIL_HOST', 'smtp.gmail.com'),
'port' => env('MAIL_PORT',25),
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'auth_mode' => null,
],
],
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'sendmail' => '/usr/sbin/sendmail -bs',
```
然后,可以在控制器、命令行等代码中使用 `Mail` 类发送邮件,例如:
```
use Illuminate\Support\Facades\Mail;
use App\Mail\OrderShipped;
Mail::to($request->user())
->cc($moreUsers)
->bcc($evenMoreUsers)
->send(new OrderShipped($order));
```
其中,`OrderShipped` 是一个发送邮件的类,可以在 `app/Mail/OrderShipped.php` 中定义:
```
namespace App\Mail;
use App\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class OrderShipped extends Mailable
{
use Queueable, SerializesModels;
/**
* The order instance.
*
* @var Order
*/
public $order;
/**
* Create a new message instance.
*
* @param \App\Order $order
* @return void
*/
public function __construct(Order $order)
{
$this->order = $order;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->view('emails.orders.shipped');
}
}
```
然后,在 `resources/views/emails/orders/shipped.blade.php` 中可以定义邮件的内容模板。
希望这些代码可以帮助您实现 Laravel 9 发送邮件的功能。
阅读全文