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.
Installation:
composer require symfony/mime
No additional configuration is required—just autoload the package.
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);
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.->html() or ->text() with template variables:
$email = (new Email())
->html(view('emails.welcome', ['user' => $user]));
$email = (new Email())
->html('<h1>HTML</h1>')
->text('Plain text fallback')
->priority(Email::PRIORITY_HIGH);
// 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);
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());
}
}
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());
}
use Symfony\Component\Mime\File\File;
$file = new File('/path/to/uploaded/file.pdf');
$mimeType = $file->getMimeType(); // e.g., 'application/pdf'
use Symfony\Component\Mime\MimeTypes;
$mimeTypes = new MimeTypes();
$mimeTypes->addType('application/vnd.myformat', 'myfile');
$mimeType = $mimeTypes->guessMimeType('document.myfile');
user@[invalid] or addresses with line breaks, per CVE-2026-45067).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(),
]);
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());
}
}
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());
}
}
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...
}
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();
});
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)
}
File::getMimeType() returns incorrect results for custom file 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'
File::getMimeTypeGuesser() to inspect guessers:
$guesser = $file->getMimeTypeGuesser();
$guesser->guessMimeType('document.pdf'); // Debug individual guessers
[email protected]) may be rejected.
Address with custom validation:
use Symfony\Component\Mime\Address;
$address = new Address('[email protected]');
if (!$address->isValid()) {
throw new \InvalidArgumentException('Invalid email address');
}
Content-ID in some versions.
filename and contentDisposition:
$attachment = new DataPart(file_get_contents('file.pdf'));
$attachment->filename = 'custom_name.pdf
How can I help you explore Laravel packages today?