【发布时间】:2018-09-17 08:48:33
【问题描述】:
我正在开发一个使用 laravel 5.6 将聊天消息发送到用户电子邮件(又名 电子邮件记录)的模块。 我需要将所有聊天消息保存到一个 txt 文件中,并将该文件作为附件发送到用户的电子邮件地址。
我不想将 txt 文件保存到我的服务器,因为很多人会使用该应用程序,它会增加服务器的存储使用量,即我需要在内存中生成 txt 文件。
我可以在没有附件的普通电子邮件中填充聊天,但如果聊天消息增加,这不是解决方案,电子邮件会太长而且对我来说似乎不专业。
到目前为止我已经尝试过: EmailTranscriptController.php
<?php
namespace App\Http\Controllers\Home;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Trade;
use App\Models\ChatMessage;
use Auth;
use Illuminate\Support\Facades\Mail;
use App\Mail\EmailTradeChatMessages;
use Validator;
class EmailTranscriptController extends Controller
{
public function emailTradeTranscript($tradeId)
{
$userId = Auth::id();
$userEmail = Auth::user()->email;
$trade = Trade::findClosedTradeByIdByUserId($tradeId, $userId);
if (is_null($trade)) {
return response()->api(false, 'Trade not available', null);
}
$tradeStartTime = $trade->created_at;
$tradeCloseTime = $trade->updated_at;
$tradeChats = ChatMessage::getAllChatByTradeId($tradeId);
Mail::to($userEmail)->queue(new EmailTradeChatMessages(
$tradeChats,
$tradeStartTime,
$tradeCloseTime
));
return response()->api(true, 'Email Sent Successfully', null);
}
}
EmailTradeChatMessages.php
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class EmailTradeChatMessages extends Mailable
{
use Queueable, SerializesModels;
protected $chats;
protected $tradeStartTime;
protected $tradeCloseTime;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($chats, $tradeStartTime, $tradeCloseTime)
{
$this->chats = $chats;
$this->tradeStartTime = $tradeStartTime;
$this->tradeCloseTime = $tradeCloseTime;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->markdown('emails.trade_chat_transcript')->with([
'chats' => $this->chats,
'tradeStartTime' => $this->tradeStartTime,
'tradeCloseTime' => $this->tradeCloseTime,
]);
}
}
trade_chat_transcript.blade.php(虚拟)
@component('mail::message')
#Trade Started at: {{$tradeStartTime}}
@php
$count=0;
@endphp
@foreach($chats as $chat)
{{++$count}}
@endforeach
#Trade Closed at: {{$tradeCloseTime}}
Thanks,<br>
{{ config('app.name') }}
@endcomponent
请帮助我获得解决方案,如果有的话,我还想获得其他解决方案。
更新
我找到了不将文件存储在服务器本身并使用 attachData() 方法附加它的解决方案,如下所示:
public function build()
{
$email= $this->markdown('emails.trade_chat_transcript')->with([
'tradeId' => $this->tradeId,
'filename' => $this->filename,
'tradeStartTime' => $this->tradeStartTime,
'tradeCloseTime' => $this->tradeCloseTime,
])
->attachData($this->message,$this->filename,[
'mime'=>'text/plain'
]);
return $email;
}
现在我需要设置要附加在电子邮件中的文件的元数据,例如。作者等
【问题讨论】:
-
但是您需要创建文件,发送后您可以删除它。检查this答案。
标签: php mongodb laravel email-attachments