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 with headers, text/HTML bodies, attachments, and multipart structures. Integrates with Symfony Mailer and standalone PHP apps; includes tools for encoding and content types.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require symfony/mime
    

    No additional configuration is required—just autoload the package.

  2. First Use Case: Create a simple email with HTML content and an attachment:

    use Symfony\Component\Mime\Email;
    use Symfony\Component\Mime\Part\DataPart;
    
    $email = (new Email())
        ->from('[email protected]')
        ->to('[email protected]')
        ->subject('Hello!')
        ->html('<h1>Hello!</h1>');
    
    // Add an attachment
    $file = new DataPart(file_get_contents('document.pdf'));
    $file->filename = 'document.pdf';
    $file->contentDisposition = 'attachment';
    $email->attach($file);
    
    // Send via SwiftMailer or Laravel's Mailer
    $transport = (new Swift_SmtpTransport('smtp.example.com', 587))
        ->setUsername('user')
        ->setPassword('pass');
    $mailer = new Swift_Mailer($transport);
    $mailer->send($email);
    
  3. Key Classes to Explore:

    • Email: For composing emails.
    • Message: For raw MIME message manipulation.
    • DataPart: For attachments or embedded content.
    • File: For detecting MIME types of files.

Implementation Patterns

Common Workflows

1. Composing Emails

  • Dynamic Content: Use ->html() or ->text() with template variables:
    $email = (new Email())
        ->html(view('emails.welcome', ['user' => $user]));
    
  • Alternatives/Related Parts: For multipart emails (e.g., HTML + text fallback):
    $email = (new Email())
        ->html('<h1>HTML</h1>')
        ->text('Plain text fallback')
        ->priority(Email::PRIORITY_HIGH);
    

2. Handling Attachments

  • Inline vs. Attachments:
    // Inline (e.g., embedded images)
    $image = new DataPart(file_get_contents('image.jpg'));
    $image->contentId = 'logo';
    $email->embed($image);
    
    // Attachment
    $file = new DataPart(file_get_contents('report.pdf'));
    $file->filename = 'report.pdf';
    $file->contentDisposition = 'attachment';
    $email->attach($file);
    
  • Laravel Integration: Use Symfony\Component\Mime\Email with Laravel’s Mailable:
    use Symfony\Component\Mime\Email as SymfonyEmail;
    
    class WelcomeMail extends Mailable {
        public function build() {
            $email = new SymfonyEmail();
            $email->from('[email protected]')
                  ->to($this->user->email)
                  ->subject('Welcome!')
                  ->html($this->renderView());
    
            return $this->markdown('emails.welcome')
                        ->withSwiftMessage($email->toSwiftMessage());
        }
    }
    

3. Parsing Incoming Emails

  • Extract Data from Raw MIME:
    use Symfony\Component\Mime\Email;
    use Symfony\Component\Mime\Header\Headers;
    
    $rawEmail = file_get_contents('email.eml');
    $email = Email::fromString($rawEmail);
    
    // Access headers
    $subject = $email->getSubject();
    $from = $email->getFrom()[0]->getAddress();
    
    // Access attachments
    foreach ($email->getAttachments() as $attachment) {
        file_put_contents("attachments/{$attachment->getFilename()}", $attachment->bodyToString());
    }
    

4. MIME Type Detection

  • For Uploaded Files:
    use Symfony\Component\Mime\File\File;
    
    $file = new File('/path/to/uploaded/file.pdf');
    $mimeType = $file->getMimeType(); // e.g., 'application/pdf'
    
  • Custom Guessers: Register additional MIME type guessers (e.g., for proprietary formats):
    use Symfony\Component\Mime\MimeTypes;
    
    $mimeTypes = new MimeTypes();
    $mimeTypes->addType('application/vnd.myformat', 'myfile');
    $mimeType = $mimeTypes->guessMimeType('document.myfile');
    

5. Validation and Sanitization

  • Reject Malformed Addresses: The package automatically validates email addresses (e.g., rejects user@[invalid] or addresses with line breaks, per CVE-2026-45067).
  • Custom Validation: Extend Email or use Symfony’s Validator:
    use Symfony\Component\Validator\Constraints as Assert;
    
    $email = new Email();
    $email->setTo(new Address('[email protected]', 'User'));
    $violations = $validator->validate($email->getTo()[0], [
        new Assert\Email(),
    ]);
    

Integration Tips

Laravel-Specific Patterns

  1. Use with laravel-notification-channels: Extend Mailable to leverage Symfony\Component\Mime\Email:

    class CustomMailer extends Mailable {
        public function build() {
            $email = new Email();
            $email->from(config('mail.from.address'))
                  ->to($this->recipient)
                  ->subject($this->subject)
                  ->html($this->renderView());
    
            return $this->withSwiftMessage($email->toSwiftMessage());
        }
    }
    
  2. Queue Email Processing: Use Laravel queues to handle bulk emails efficiently:

    class SendEmailJob implements ShouldQueue {
        public function handle() {
            $email = (new Email())
                ->from('[email protected]')
                ->to('[email protected]')
                ->subject('Your Update')
                ->html('...');
    
            Mail::send($email->toSwiftMessage());
        }
    }
    
  3. File Uploads with MIME Detection: Validate uploads before storage:

    use Symfony\Component\Mime\File\File;
    
    public function store(Request $request) {
        $file = new File($request->file('document')->getPathname());
        $mimeType = $file->getMimeType();
    
        if (!str_starts_with($mimeType, 'application/pdf')) {
            throw new \Exception('Invalid file type');
        }
    
        // Store file...
    }
    

Performance Optimizations

  1. Cache MIME Type Guessers: Cache results for frequently accessed files:

    $cache = new \Symfony\Component\Cache\Simple\FilesystemCache();
    $file = new File('document.pdf');
    $mimeType = $cache->get('mime_type_' . $file->getPathname(), function() use ($file) {
        return $file->getMimeType();
    });
    
  2. Batch Processing: Process emails in chunks for bulk operations:

    $emails = Email::fromString($rawBatch);
    foreach ($emails as $email) {
        // Process each email (e.g., parse, store, or forward)
    }
    

Gotchas and Tips

Pitfalls and Debugging

1. MIME Type Detection Issues

  • Problem: File::getMimeType() returns incorrect results for custom file types.
    • Fix: Register custom MIME types:
      $mimeTypes = new MimeTypes();
      $mimeTypes->addType('application/vnd.myapp', 'myext');
      $file = new File('document.myapp', null, $mimeTypes);
      $mimeType = $file->getMimeType(); // Now returns 'application/vnd.myapp'
      
  • Debugging: Use File::getMimeTypeGuesser() to inspect guessers:
    $guesser = $file->getMimeTypeGuesser();
    $guesser->guessMimeType('document.pdf'); // Debug individual guessers
    

2. Email Address Validation

  • Problem: Custom email addresses (e.g., [email protected]) may be rejected.
    • Fix: Use Address with custom validation:
      use Symfony\Component\Mime\Address;
      
      $address = new Address('[email protected]');
      if (!$address->isValid()) {
          throw new \InvalidArgumentException('Invalid email address');
      }
      

3. Attachment Filenames and Content-Disposition

  • Problem: Filenames in attachments are overwritten by Content-ID in some versions.
    • Fix: Explicitly set filename and contentDisposition:
      $attachment = new DataPart(file_get_contents('file.pdf'));
      $attachment->filename = 'custom_name.pdf
      
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle