SendEmailMessage.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace App\Jobs;
  3. use Illuminate\Bus\Queueable;
  4. use Illuminate\Contracts\Queue\ShouldQueue;
  5. use Illuminate\Foundation\Bus\Dispatchable;
  6. use Illuminate\Queue\InteractsWithQueue;
  7. use Illuminate\Queue\SerializesModels;
  8. use Illuminate\Support\Facades\Mail;
  9. class SendEmailMessage implements ShouldQueue
  10. {
  11. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  12. public function __construct(public int $messageId) {}
  13. public function handle()
  14. {
  15. $msg = \App\Models\EmailMessage::with(['recipients', 'attachments'])->findOrFail($this->messageId);
  16. $msg->update(['status' => 'processing']);
  17. try {
  18. $attachments = $msg->attachments
  19. ->map(fn($a) => [
  20. 'disk' => $a->disk,
  21. 'path' => $a->path,
  22. 'name' => $a->name ?? basename($a->path),
  23. ])
  24. ->values()->all();
  25. } catch (\Throwable $e) {
  26. $msg->update(['status' => 'failed', 'error_message' => $e->getMessage()]);
  27. }
  28. foreach ($msg->recipients as $r) {
  29. if (in_array($r->status, ['sent', 'failed'])) continue;
  30. try {
  31. $mailable = new \App\Mail\GenericMail(
  32. $msg->subject,
  33. $msg->content_html,
  34. $attachments
  35. );
  36. Mail::to($r->email_address)->send($mailable);
  37. $r->update(['status' => 'sent', 'sent_at' => now(), 'error_message' => null]);
  38. } catch (\Throwable $e) {
  39. $r->update(['status' => 'failed', 'error_message' => $e->getMessage()]);
  40. }
  41. }
  42. $total = $msg->recipients()->count();
  43. $sent = $msg->recipients()->where('status', 'sent')->count();
  44. $failed = $msg->recipients()->where('status', 'failed')->count();
  45. $newStatus = 'draft';
  46. if ($total === 0) {
  47. $newStatus = 'draft';
  48. } elseif ($sent === $total) {
  49. $newStatus = 'sent';
  50. } elseif ($sent > 0 && $failed > 0) {
  51. $newStatus = 'partial';
  52. } else {
  53. $newStatus = 'failed';
  54. }
  55. $msg->update([
  56. 'status' => $newStatus,
  57. 'sent_at' => $sent > 0 ? now() : $msg->sent_at,
  58. ]);
  59. }
  60. }