Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Email Service Laravel Package

doitcloud/email-service

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation & Configuration

    • Require the package:
      composer require doitcloud/email-service
      
    • Publish the config:
      php artisan vendor:publish --tag=emailservice-config
      
    • Update config/emailservice.php with your Office365 API credentials (tenant_id, client_id, client_secret, etc.).
  2. First Use Case: Sending an Email

    • Inject the SendEmail controller into a route or service:
      use Doitcloud\EmailService\Http\Controllers\SendEmail;
      
      Route::post('/send-email', function () {
          $sender = new SendEmail();
          $response = $sender->send([
              'to' => 'recipient@example.com',
              'subject' => 'Test Email',
              'body' => 'Hello from Laravel!'
          ]);
          return $response;
      });
      
    • Verify credentials by testing with a dummy email.

Implementation Patterns

Common Workflows

  1. Reusable Email Service Class

    • Extend or wrap the SendEmail controller in a service class for cleaner dependency injection:
      namespace App\Services;
      
      use Doitcloud\EmailService\Http\Controllers\SendEmail;
      
      class EmailService {
          protected $sender;
      
          public function __construct(SendEmail $sender) {
              $this->sender = $sender;
          }
      
          public function sendTo($email, $subject, $body) {
              return $this->sender->send([
                  'to' => $email,
                  'subject' => $subject,
                  'body' => $body
              ]);
          }
      }
      
    • Register the service in AppServiceProvider:
      $this->app->bind(EmailService::class, function ($app) {
          return new EmailService(new SendEmail());
      });
      
  2. Queueing Emails for Async Processing

    • Dispatch emails via Laravel queues to avoid blocking requests:
      use Illuminate\Support\Facades\Queue;
      
      Queue::push(function () {
          $sender = new SendEmail();
          $sender->send([...]);
      });
      
  3. Dynamic Configuration per Environment

    • Use Laravel’s config caching or environment variables to switch between dev/staging/prod Office365 setups:
      config(['emailservice.tenant_id' => env('OFFICE365_TENANT_ID')]);
      
  4. Logging & Error Handling

    • Wrap the send() call in a try-catch to log failures:
      try {
          $response = $sender->send([...]);
      } catch (\Exception $e) {
          \Log::error("Email failed: " . $e->getMessage());
          throw $e; // Or return a user-friendly message
      }
      

Gotchas and Tips

Pitfalls & Debugging

  1. Authentication Failures

    • Symptom: 401 Unauthorized or empty responses.
    • Fix:
      • Double-check tenant_id, client_id, and client_secret in config/emailservice.php.
      • Ensure the scope includes https://graph.microsoft.com/.default for OAuth2.
      • Verify the login_domain matches your Office365 tenant (e.g., yourcompany.onmicrosoft.com).
  2. CORS or Endpoint Issues

    • Symptom: 404 Not Found or CORS errors when testing locally.
    • Fix:
      • Confirm send_email_url in config points to the correct Office365 Graph API endpoint (e.g., https://graph.microsoft.com/v1.0/sendMail).
      • For local testing, use Postman or cURL to isolate whether the issue is client-side or API-side.
  3. Rate Limiting

    • Office365 may throttle requests. Implement exponential backoff in retries:
      use Symfony\Component\HttpClient\Retry\RetryStrategy;
      
      $client = \Http::withOptions([
          'retry' => RetryStrategy::fromCalls(3, function () {
              return true; // Retry on any failure
          })
      ]);
      
  4. Missing Dependencies

    • Symptom: Class 'Doitcloud\EmailService\Http\Controllers\SendEmail' not found.
    • Fix:
      • Ensure the package is autoloaded (run composer dump-autoload).
      • Check for namespace collisions if using a similar class name elsewhere.

Extension Points

  1. Custom Email Templates

    • Override the send() method to support Markdown/HTML templates:
      $sender->send([
          'to' => 'user@example.com',
          'subject' => 'Welcome!',
          'body' => view('emails.welcome', ['name' => 'John'])->render()
      ]);
      
  2. Attachment Support

    • Extend the package to handle file attachments by modifying the SendEmail controller to accept an attachments array:
      $sender->send([
          'to' => 'user@example.com',
          'attachments' => [storage_path('file.pdf')]
      ]);
      
  3. Event Dispatching

    • Trigger Laravel events (e.g., EmailSent) after successful sends:
      event(new \App\Events\EmailSent($response));
      
  4. Testing

    • Mock the SendEmail controller in PHPUnit:
      $mockSender = Mockery::mock(SendEmail::class);
      $mockSender->shouldReceive('send')->andReturn(['success' => true]);
      $this->app->instance(SendEmail::class, $mockSender);
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver