Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[Mime] Simplify adding Parts to an Email #47462

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions 10 src/Symfony/Bridge/Twig/Tests/Mime/TemplatedEmailTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,16 @@ public function testSymfonySerialize()
"htmlCharset": null,
"attachments": [
{
"filename": "test.txt",
"mediaType": "application",
"body": "Some Text file",
"charset": null,
"subtype": "octet-stream",
"disposition": "attachment",
"name": "test.txt",
"content-type": null,
"inline": false
"encoding": "base64",
"headers": [],
"class": "Symfony\\\Component\\\Mime\\\Part\\\DataPart"
}
],
"headers": {
Expand Down
2 changes: 1 addition & 1 deletion 2 src/Symfony/Bridge/Twig/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
"symfony/security-core": "^5.4|^6.0",
"symfony/security-csrf": "^5.4|^6.0",
"symfony/security-http": "^5.4|^6.0",
"symfony/serializer": "^5.4|^6.0",
"symfony/serializer": "^6.2",
"symfony/stopwatch": "^5.4|^6.0",
"symfony/console": "^5.4|^6.0",
"symfony/expression-language": "^5.4|^6.0",
Expand Down
2 changes: 1 addition & 1 deletion 2 src/Symfony/Component/Mailer/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
"psr/event-dispatcher": "^1",
"psr/log": "^1|^2|^3",
"symfony/event-dispatcher": "^5.4|^6.0",
"symfony/mime": "^5.4|^6.0",
"symfony/mime": "^6.2",
"symfony/service-contracts": "^1.1|^2|^3"
},
"require-dev": {
Expand Down
90 changes: 15 additions & 75 deletions 90 src/Symfony/Component/Mime/Email.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Symfony\Component\Mime\Exception\LogicException;
use Symfony\Component\Mime\Part\AbstractPart;
use Symfony\Component\Mime\Part\BodyFile;
use Symfony\Component\Mime\Part\DataPart;
use Symfony\Component\Mime\Part\Multipart\AlternativePart;
use Symfony\Component\Mime\Part\Multipart\MixedPart;
Expand Down Expand Up @@ -326,25 +327,15 @@ public function getHtmlCharset(): ?string
*/
public function attach($body, string $name = null, string $contentType = null): static
{
if (!\is_string($body) && !\is_resource($body)) {
throw new \TypeError(sprintf('The body must be a string or a resource (got "%s").', get_debug_type($body)));
}

$this->cachedBody = null;
$this->attachments[] = ['body' => $body, 'name' => $name, 'content-type' => $contentType, 'inline' => false];

return $this;
return $this->attachPart(new DataPart($body, $name, $contentType));
}

/**
* @return $this
*/
public function attachFromPath(string $path, string $name = null, string $contentType = null): static
{
$this->cachedBody = null;
$this->attachments[] = ['path' => $path, 'name' => $name, 'content-type' => $contentType, 'inline' => false];

return $this;
return $this->attachPart(new DataPart(new BodyFile($path), $name, $contentType));
}

/**
Expand All @@ -354,25 +345,15 @@ public function attachFromPath(string $path, string $name = null, string $conten
*/
public function embed($body, string $name = null, string $contentType = null): static
{
if (!\is_string($body) && !\is_resource($body)) {
throw new \TypeError(sprintf('The body must be a string or a resource (got "%s").', get_debug_type($body)));
}

$this->cachedBody = null;
$this->attachments[] = ['body' => $body, 'name' => $name, 'content-type' => $contentType, 'inline' => true];

return $this;
return $this->attachPart((new DataPart($body, $name, $contentType))->asInline());
}

/**
* @return $this
*/
public function embedFromPath(string $path, string $name = null, string $contentType = null): static
{
$this->cachedBody = null;
$this->attachments[] = ['path' => $path, 'name' => $name, 'content-type' => $contentType, 'inline' => true];

return $this;
return $this->attachPart((new DataPart(new BodyFile($path), $name, $contentType))->asInline());
}

/**
Expand All @@ -381,22 +362,17 @@ public function embedFromPath(string $path, string $name = null, string $content
public function attachPart(DataPart $part): static
{
$this->cachedBody = null;
$this->attachments[] = ['part' => $part];
$this->attachments[] = $part;

return $this;
}

/**
* @return array|DataPart[]
* @return DataPart[]
*/
public function getAttachments(): array
{
$parts = [];
foreach ($this->attachments as $attachment) {
$parts[] = $this->createDataPart($attachment);
}

return $parts;
return $this->attachments;
}

public function getBody(): AbstractPart
Expand Down Expand Up @@ -502,35 +478,23 @@ private function prepareParts(): ?array
}

$otherParts = $relatedParts = [];
foreach ($this->attachments as $attachment) {
$part = $this->createDataPart($attachment);
if (isset($attachment['part'])) {
$attachment['name'] = $part->getName();
}

$related = false;
foreach ($this->attachments as $part) {
foreach ($names as $name) {
if ($name !== $attachment['name']) {
if ($name !== $part->getName()) {
continue;
}
if (isset($relatedParts[$name])) {
continue 2;
}
$part->setDisposition('inline');

$html = str_replace('cid:'.$name, 'cid:'.$part->getContentId(), $html, $count);
if ($count) {
$related = true;
}
$part->setName($part->getContentId());
$relatedParts[$name] = $part;
$part->setName($part->getContentId())->asInline();

break;
continue 2;
}

if ($related) {
$relatedParts[$attachment['name']] = $part;
} else {
$otherParts[] = $part;
}
$otherParts[] = $part;
}
if (null !== $htmlPart) {
$htmlPart = new TextPart($html, $this->htmlCharset, 'html');
Expand All @@ -539,24 +503,6 @@ private function prepareParts(): ?array
return [$htmlPart, $otherParts, array_values($relatedParts)];
}

private function createDataPart(array $attachment): DataPart
{
if (isset($attachment['part'])) {
return $attachment['part'];
}

if (isset($attachment['body'])) {
$part = new DataPart($attachment['body'], $attachment['name'] ?? null, $attachment['content-type'] ?? null);
} else {
$part = DataPart::fromPath($attachment['path'] ?? '', $attachment['name'] ?? null, $attachment['content-type'] ?? null);
}
if ($attachment['inline']) {
$part->asInline();
}

return $part;
}

/**
* @return $this
*/
Expand Down Expand Up @@ -606,12 +552,6 @@ public function __serialize(): array
$this->html = (new TextPart($this->html))->getBody();
}

foreach ($this->attachments as $i => $attachment) {
if (isset($attachment['body']) && \is_resource($attachment['body'])) {
$this->attachments[$i]['body'] = (new TextPart($attachment['body']))->getBody();
}
}

return [$this->text, $this->textCharset, $this->html, $this->htmlCharset, $this->attachments, parent::__serialize()];
}

Expand Down
5 changes: 1 addition & 4 deletions 5 src/Symfony/Component/Mime/MessageConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,7 @@ private static function attachParts(Email $email, array $parts): Email
throw new RuntimeException(sprintf('Unable to create an Email from an instance of "%s" as the body is too complex.', get_debug_type($email)));
}

$headers = $part->getPreparedHeaders();
$method = 'inline' === $headers->getHeaderBody('Content-Disposition') ? 'embed' : 'attach';
$name = $headers->getHeaderParameter('Content-Disposition', 'filename');
$email->$method($part->getBody(), $name, $part->getMediaType().'/'.$part->getMediaSubtype());
$email->attachPart($part);
}

return $email;
Expand Down
42 changes: 42 additions & 0 deletions 42 src/Symfony/Component/Mime/Part/BodyFile.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Mime\Part;

use Symfony\Component\Mime\MimeTypes;

/**
* @author Fabien Potencier <fabien@symfony.com>
*/
class BodyFile
{
private static $mimeTypes;

public function __construct(
private string $path,
) {
}

public function getPath(): string
{
return $this->path;
}

public function getContentType(): string
{
$ext = strtolower(pathinfo($this->path, \PATHINFO_EXTENSION));
if (null === self::$mimeTypes) {
self::$mimeTypes = new MimeTypes();
}

return self::$mimeTypes->getMimeTypes($ext)[0] ?? 'application/octet-stream';
}
}
46 changes: 7 additions & 39 deletions 46 src/Symfony/Component/Mime/Part/DataPart.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@

use Symfony\Component\Mime\Exception\InvalidArgumentException;
use Symfony\Component\Mime\Header\Headers;
use Symfony\Component\Mime\MimeTypes;

/**
* @author Fabien Potencier <fabien@symfony.com>
Expand All @@ -23,22 +22,23 @@ class DataPart extends TextPart
/** @internal */
protected $_parent;

private static $mimeTypes;

private $filename;
private $mediaType;
private $cid;
private $handle;

/**
* @param resource|string $body
nicolas-grekas marked this conversation as resolved.
Show resolved Hide resolved
* @param resource|string|BodyFile $body Use a BodyFile instance to defer loading the file until rendering
*/
public function __construct($body, string $filename = null, string $contentType = null, string $encoding = null)
{
unset($this->_parent);

if ($body instanceof BodyFile && !$filename) {
$filename = basename($body->getPath());
}

if (null === $contentType) {
$contentType = 'application/octet-stream';
$contentType = $body instanceof BodyFile ? $body->getContentType() : 'application/octet-stream';
}
[$this->mediaType, $subtype] = explode('/', $contentType);

Expand All @@ -53,32 +53,7 @@ public function __construct($body, string $filename = null, string $contentType

public static function fromPath(string $path, string $name = null, string $contentType = null): self
{
if (null === $contentType) {
$ext = strtolower(substr($path, strrpos($path, '.') + 1));
if (null === self::$mimeTypes) {
self::$mimeTypes = new MimeTypes();
}
$contentType = self::$mimeTypes->getMimeTypes($ext)[0] ?? 'application/octet-stream';
}

if ((is_file($path) && !is_readable($path)) || is_dir($path)) {
throw new InvalidArgumentException(sprintf('Path "%s" is not readable.', $path));
}

if (false === $handle = @fopen($path, 'r', false)) {
throw new InvalidArgumentException(sprintf('Unable to open path "%s".', $path));
}

if (!is_file($path)) {
$cache = fopen('php://temp', 'r+');
stream_copy_to_stream($handle, $cache);
$handle = $cache;
}

$p = new self($handle, $name ?: basename($path), $contentType);
$p->handle = $handle;

return $p;
return new self(new BodyFile($path), $name, $contentType);
}

/**
Expand Down Expand Up @@ -158,13 +133,6 @@ private function generateContentId(): string
return bin2hex(random_bytes(16)).'@symfony';
}

public function __destruct()
{
if (null !== $this->handle && \is_resource($this->handle)) {
fclose($this->handle);
}
}

public function __sleep(): array
{
// converts the body to a string
Expand Down
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.