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

Laminas Mime Laravel Package

laminas/laminas-mime

Laminas MIME component for handling MIME messages and parts. Note: this package is abandoned and will receive no further development. For an actively maintained alternative, consider symfony/mime or zbateson/mail-mime-parser.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require laminas/laminas-mime
    

    (Note: Due to the package being abandoned, prefer alternatives like symfony/mime for new projects.)

  2. Basic Usage:

    use Laminas\Mime\Message;
    use Laminas\Mime\Part;
    
    // Create a simple text part
    $textPart = new Part('Hello, World!');
    $textPart->type = 'text/plain';
    $textPart->charset = 'UTF-8';
    
    // Create a multipart message
    $message = new Message();
    $message->addPart($textPart);
    
    // Output the raw MIME message
    echo $message->generateMessage();
    
  3. First Use Case:

    • Parsing an incoming email attachment:
      $rawEmail = file_get_contents('email.eml');
      $message = Message::fromString($rawEmail);
      foreach ($message->getParts() as $part) {
          if ($part->isAttachment()) {
              echo 'Attachment: ' . $part->filename . "\n";
          }
      }
      

Where to Look First

  • Documentation for class references and API details.
  • Source Code for implementation examples (e.g., Part, Message, Header).
  • Laminas Mail (if using for email workflows, as this package is often paired with it).

Implementation Patterns

Core Workflows

1. Building Multipart Messages

  • Pattern: Use Laminas\Mime\Message as a container for Part objects.
  • Example:
    $message = new Message();
    $message->setEncoding('7bit'); // Default encoding for the message
    
    // Add a text part
    $textPart = new Part('Plain text content');
    $textPart->type = 'text/plain';
    $textPart->charset = 'UTF-8';
    $message->addPart($textPart);
    
    // Add an HTML part
    $htmlPart = new Part('<b>HTML content</b>');
    $htmlPart->type = 'text/html';
    $htmlPart->charset = 'UTF-8';
    $message->addPart($htmlPart);
    
    // Generate the final MIME message
    $rawMessage = $message->generateMessage();
    

2. Handling Attachments

  • Pattern: Use Part::fromFile() or Part::fromString() for attachments.
  • Example:
    $attachment = new Part(file_get_contents('file.pdf'));
    $attachment->type = 'application/pdf';
    $attachment->filename = 'document.pdf';
    $attachment->disposition = 'attachment';
    $message->addPart($attachment);
    

3. Parsing Incoming MIME Messages

  • Pattern: Use Message::fromString() to parse raw MIME data.
  • Example:
    $rawEmail = file_get_contents('email.eml');
    $message = Message::fromString($rawEmail);
    
    foreach ($message->getParts() as $part) {
        if ($part->type === 'text/html') {
            echo $part->content; // HTML content
        }
    }
    

4. Custom Headers and Encoding

  • Pattern: Manually set headers or use encoding utilities.
  • Example:
    $message->getHeaders()->addHeaderLine('X-Custom-Header', 'value');
    $encodedContent = $message->encodeContent($plainText, 'quoted-printable');
    

Integration Tips

  • With Laravel Mail: Use laminas/mime to customize MIME parts before passing them to Laravel’s MimeMessage:

    use Laminas\Mime\Part;
    use Illuminate\Mail\MimeMessage;
    
    $part = new Part('<h1>Hello</h1>', 'text/html');
    $mimeMessage = new MimeMessage();
    $mimeMessage->withPart($part);
    
  • With File Uploads: Dynamically generate MIME parts from uploaded files:

    $file = request()->file('attachment');
    $part = new Part(file_get_contents($file->path()));
    $part->filename = $file->getClientOriginalName();
    $part->type = mime_content_type($file->path());
    
  • Streaming Large Files: Avoid loading entire files into memory by streaming content:

    $part = new Part();
    $part->setContentStream(function () {
        yield file_get_contents('large-file.pdf');
    });
    $part->type = 'application/pdf';
    

Gotchas and Tips

Pitfalls

  1. Deprecation Warning:

    • The package is abandoned. Avoid using it in new projects; prefer symfony/mime or zbateson/mail-mime-parser.
    • If maintaining legacy code, pin to a specific version (e.g., 2.12.0) to avoid breaking changes.
  2. PHP Version Support:

    • Minimum PHP 7.3 (as of v2.8.0). Older versions may throw errors.
    • PHP 8.3 support was added in v2.12.0, but no further updates are expected.
  3. Header Folding Issues:

    • Long headers may not fold correctly. Use Header::fold() explicitly:
      $header = new Header\ContentType('text/plain; charset=UTF-8');
      $header->fold(76); // Fold at 76 chars (RFC 2822 compliant)
      
  4. Encoding Quirks:

    • quoted-printable encoding for large strings can be memory-intensive (fixed in v2.7.3, but still a risk for huge payloads).
    • Always specify charset for non-ASCII content to avoid corruption.
  5. Boundary Generation:

    • Random boundaries are generated by default. For testing, set a fixed boundary:
      $message->setBoundary('fixed-boundary-string');
      

Debugging Tips

  1. Inspect Raw MIME Output: Use generateMessage() to debug the final output:

    echo htmlspecialchars($message->generateMessage());
    
  2. Validate Headers: Check for malformed headers with:

    $headers = $message->getHeaders();
    foreach ($headers as $header) {
        echo $header->getFieldName() . ': ' . $header->getFieldValue() . "\n";
    }
    
  3. Handle Encoding Errors: If content appears garbled, explicitly set the encoding:

    $part->encoding = 'base64'; // Force base64 for binary data
    

Extension Points

  1. Custom Part Types: Extend Laminas\Mime\Part to add domain-specific logic:

    class CustomPart extends Part {
        public function isValid() {
            return $this->type === 'application/vnd.custom';
        }
    }
    
  2. Override Encoding: Replace the default encoder by injecting a custom strategy:

    $message->setEncodingStrategy(function ($content, $encoding) {
        return custom_encode($content, $encoding);
    });
    
  3. Hook into Message Generation: Use events (if supported in your Laravel version) or wrap generateMessage():

    $rawMessage = $message->generateMessage();
    $rawMessage = preg_replace('/custom-pattern/', 'replacement', $rawMessage);
    

Configuration Quirks

  • No Laravel Config: Unlike Laravel packages, laminas/mime has no config file. All settings are runtime (e.g., boundaries, encodings).
  • Default Charset: Defaults to UTF-8, but explicitly set it for non-English content to avoid issues:
    $part->charset = 'ISO-8859-1'; // For legacy systems
    

Performance Considerations

  • Memory Usage: Large attachments or base64-encoded content can bloat memory. Use streams for files >10MB:
    $part->setContentStream(function () use ($filePath) {
        yield file_get_contents($filePath);
    });
    
  • Avoid Redundant Parsing: Cache parsed messages if reprocessing the same MIME data:
    $cachedMessage = Message::fromString($rawEmail, ['cache' => true]);
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope