laravel使用guzzlehttp/guzzle发送邮件
时间: 2023-11-27 14:36:37 浏览: 46
在 Laravel 中使用 GuzzleHttp/Guzzle 发送邮件可以通过以下步骤实现:
1. 安装 GuzzleHttp/Guzzle
可以使用 Composer 进行安装:
```
composer require guzzlehttp/guzzle
```
2. 创建邮件发送类
在 app 目录下创建一个名为 MailSender 的类,代码如下:
```php
<?php
namespace App;
use GuzzleHttp\Client;
class MailSender
{
protected $client;
public function __construct()
{
$this->client = new Client([
'base_uri' => 'https://api.sendgrid.com/v3/',
'headers' => [
'Authorization' => 'Bearer ' . env('SENDGRID_API_KEY'),
'Content-Type' => 'application/json'
]
]);
}
public function send($to, $subject, $content)
{
$response = $this->client->request('POST', 'mail/send', [
'json' => [
'personalizations' => [
[
'to' => [
[
'email' => $to
]
]
]
],
'from' => [
'email' => 'sender@example.com'
],
'subject' => $subject,
'content' => [
[
'type' => 'text/plain',
'value' => $content
]
]
]
]);
return $response->getStatusCode();
}
}
```
其中,使用 GuzzleHttp\Client 创建一个 HTTP 客户端,设置 base_uri 为 SendGrid 邮件服务的 API 地址,headers 中包含 Authorization 和 Content-Type 信息。send() 方法接受收件人邮箱地址、邮件主题和邮件内容,使用 HTTP POST 请求发送邮件。
3. 在控制器中使用 MailSender 发送邮件
在需要发送邮件的控制器中,使用 MailSender 类发送邮件,示例代码如下:
```php
<?php
namespace App\Http\Controllers;
use App\MailSender;
use Illuminate\Http\Request;
class MailController extends Controller
{
public function send(Request $request)
{
$to = $request->input('to');
$subject = $request->input('subject');
$content = $request->input('content');
$mailSender = new MailSender();
$statusCode = $mailSender->send($to, $subject, $content);
return response()->json(['status' => $statusCode]);
}
}
```
在 send() 方法中,从请求中获取收件人邮箱地址、邮件主题和邮件内容,然后实例化 MailSender 类并调用 send() 方法发送邮件。
4. 配置 SendGrid API 密钥
在 .env 文件中添加 SendGrid API 密钥:
```
SENDGRID_API_KEY=your_api_key_here
```
至此,使用 GuzzleHttp/Guzzle 发送邮件的配置就完成了。