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

Mime Laravel Package

symfony/mime

Symfony MIME component for creating and parsing MIME messages: build emails and attachments, manage headers, encoders, addresses, and content types. Works standalone or with Symfony Mailer. Includes docs, contribution guidelines, and issue tracking.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation (Laravel already includes it; standalone via Composer):

    composer require symfony/mime
    

    For Laravel users, no action needed—it’s bundled with symfony/mailer.

  2. First Use Case: Sending a Basic Email

    use Symfony\Component\Mime\Email;
    use Symfony\Component\Mime\Address;
    
    $email = (new Email())
        ->from(new Address('sender@example.com', 'Sender Name'))
        ->to('recipient@example.com')
        ->subject('Test Email')
        ->text('Plain text content')
        ->html('<h1>HTML content</h1>');
    
    // Send via Symfony Mailer (Laravel uses this under the hood)
    $mailer->send($email);
    
  3. Key Classes to Know:

    • Email: High-level API for emails (subject, headers, bodies).
    • Message: Core MIME message structure (headers, body parts).
    • Part: Represents individual parts (attachments, embedded images).
    • Address: Standardized email addresses (supports display names).
    • MimeTypes: Guesses MIME types from file extensions/content.
  4. Where to Look First:


Implementation Patterns

1. Email Composition Workflows

Transactional Emails (Laravel Facade)

// Using Laravel's Mail facade (recommended for simplicity)
Mail::send([], [], function ($message) use ($user) {
    $message->to($user->email)
            ->subject('Your Account Update')
            ->markdown('emails.account_update') // Blade template
            ->with(['user' => $user]);

    // Attachments
    $message->attach(storage_path('app/report.pdf'), [
        'as' => 'monthly_report.pdf',
        'mime' => 'application/pdf',
    ]);

    // Inline images (e.g., for HTML emails)
    $message->embed(public_path('images/logo.png'), 'logo_id');
});

Pattern: Use Laravel’s Mail facade for templates, fall back to Symfony\Component\Mime\Email for complex logic.

Multipart Emails (Symfony API)

$email = (new Email())
    ->from('no-reply@example.com')
    ->to('user@example.com')
    ->subject('Newsletter')
    // Plain-text fallback
    ->text('Plain text version...')
    // HTML with embedded image
    ->html('<img src="cid:logo">')
    ->attachFromPath(public_path('images/logo.png'), 'logo.png', 'image/png')
    ->priority(Email::PRIORITY_HIGH);

// Add a custom header
$email->getHeaders()->addTextHeader('X-Sender', 'Automated System');

2. Attachments and Embedded Resources

Dynamic Attachments

// Attach a file with custom name and MIME type
$email->attach(
    file_get_contents(storage_path('app/generated.pdf')),
    'custom_name.pdf',
    'application/pdf'
);

// Stream large files to avoid memory issues
$email->attach(
    fopen(storage_path('app/large_file.zip'), 'r'),
    'large_file.zip',
    'application/zip'
);

Embedded Images (CID)

// Embed an image for HTML emails
$email->embed(public_path('images/product.jpg'), 'product_id');

// Reference in HTML
$email->html('<img src="cid:product_id" alt="Product">');

3. Parsing Incoming Emails

use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Message;

// Parse raw email content (e.g., from a mailbox)
$message = Message::fromString($rawEmailContent);
$email = Email::fromMessage($message);

// Access parts
foreach ($email->getAttachments() as $attachment) {
    $attachment->getBody(); // File content
    $attachment->getFilename(); // Original name
}

foreach ($email->getHtmlBody() as $htmlPart) {
    $htmlPart->getBody(); // HTML content
}

4. Integration with Laravel

Custom Mailable Classes

use Illuminate\Mail\Mailable;
use Symfony\Component\Mime\Email;

class CustomMailable extends Mailable
{
    public function build()
    {
        $email = (new Email())
            ->from('app@example.com')
            ->to($this->recipient)
            ->subject('Custom Email');

        // Add multipart content
        $email->text('Plain text')
              ->html('<h1>HTML</h1>');

        // Attachments
        $email->attach(storage_path('app/file.pdf'));

        return $this->withSymfonyEmail($email);
    }
}

Using Symfony MIME Directly in Controllers

use Symfony\Component\Mime\Email;
use Symfony\Component\Mailer\MailerInterface;

public function sendWelcomeEmail(User $user)
{
    $email = (new Email())
        ->from('welcome@example.com')
        ->to($user->email)
        ->subject('Welcome!')
        ->html(view('emails.welcome', ['user' => $user])->render());

    $this->mailer->send($email);
}

5. Advanced: Custom Headers and Encodings

// Add custom headers
$email->getHeaders()
      ->addTextHeader('X-Priority', '1')
      ->addTextHeader('List-Unsubscribe', '<mailto:unsubscribe@example.com>');

// Force encoding (e.g., for non-UTF-8 content)
$email->getHeaders()->setParameter('Content-Type', 'text/plain; charset=ISO-8859-1');

6. Testing Emails

// Use Laravel’s Mail fake or Symfony’s MailerMock
$mailer = new Mailer(new TransportMock());
$email = (new Email())->to('test@example.com')->subject('Test');
$mailer->send($email);

// Assert sent emails
$sentEmails = $mailer->getSentEmails();
$this->assertCount(1, $sentEmails);

Gotchas and Tips

Common Pitfalls

  1. MIME Type Guessing Failures

    • Issue: FileBinaryMimeTypeGuesser may misidentify file types (e.g., .php files as text).
    • Fix: Explicitly set MIME types:
      $email->attach($file, 'custom.pdf', 'application/pdf');
      
    • Debug: Use MimeTypes::getDefault() to inspect guessed types.
  2. Inline Images Not Displaying

    • Issue: cid: references in HTML don’t match embedded content IDs.
    • Fix: Ensure consistent IDs:
      $email->embed($path, 'unique_id_123'); // Embed
      $email->html('<img src="cid:unique_id_123">'); // Reference
      
  3. Memory Leaks with Large Attachments

    • Issue: Loading entire files into memory with file_get_contents().
    • Fix: Stream files using fopen() or SplFileInfo:
      $email->attach(fopen($path, 'r'), $name, $mime);
      
  4. Header Injection Vulnerabilities

    • Issue: Malicious input in headers (e.g., Bcc:, Reply-To).
    • Fix: Sanitize inputs or use Address objects:
      $email->to(new Address('user@example.com')); // Safe
      $email->to('user@example.com'); // Less safe (no validation)
      
  5. PHP 8.4+ Deprecations

    • Issue: __sleep()/__wakeup() in AbstractPart are deprecated (replaced with __serialize()).
    • Fix: Upgrade to Symfony 8.0+ or avoid custom AbstractPart subclasses.
  6. Charset Mismatches

    • Issue: Non-UTF-8 content (e.g., ISO-8859-1) breaks rendering.
    • Fix: Explicitly set charset:
      $email->text($content, 'ISO-8859-1');
      
  7. Multipart Boundary Collisions

    • Issue: Custom boundaries may conflict with existing parts.
    • Fix: Let Symfony generate boundaries:
      $email->html('<p>Content</p>'); // Auto-handled
      

Debugging Tips

  1. Inspect Raw MIME Output
    $raw = $email->toString();
    file_put_contents
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport