Skip to content

Commit cb28a21

Browse files
Merge pull request #309 from mp-network-development/fix/blob-attachment-double-encoding
Fix double base64 encoding of blob attachments in CakePHP 5
1 parent e8d3d54 commit cb28a21

2 files changed

Lines changed: 25 additions & 1 deletion

File tree

src/Mailer/Message.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -430,8 +430,8 @@ protected function attachInlineFiles(?string $boundary = null): array {
430430
continue;
431431
}
432432
if (!empty($fileInfo['data'])) {
433+
// CakePHP 5's setAttachments() already base64 encodes blob data
433434
$data = $fileInfo['data'];
434-
$data = chunk_split(base64_encode($data));
435435
} elseif (!empty($fileInfo['file'])) {
436436
$data = $this->_readFile($fileInfo['file']);
437437
} else {

tests/TestCase/Mailer/MessageTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,30 @@ public function testAddEmbeddedAttachment() {
168168
$this->assertSame($expected, $image);
169169
}
170170

171+
/**
172+
* @return void
173+
*/
174+
public function testAttachInlineBlobNotDoubleEncoded() {
175+
$file = Plugin::path('Tools') . 'tests' . DS . 'test_files' . DS . 'img' . DS . 'hotel.png';
176+
$originalContent = file_get_contents($file);
177+
178+
$this->message->setEmailFormat('both');
179+
$this->message->setTo('test@example.com');
180+
$this->message->setFrom('from@example.com');
181+
$this->message->addEmbeddedBlobAttachment($originalContent, 'hotel.png');
182+
183+
$body = $this->message->getBodyString();
184+
185+
// Extract base64 data block from the body after Content-Transfer-Encoding: base64
186+
preg_match('/Content-Transfer-Encoding: base64\r?\n.*?\r?\n\r?\n(.+?)(?:\r?\n\r?\n|--)/s', $body, $matches);
187+
$this->assertNotEmpty($matches[1], 'Could not find base64 data in body');
188+
189+
$encodedData = trim($matches[1]);
190+
$decoded = base64_decode($encodedData, true);
191+
$this->assertNotFalse($decoded, 'Data should be valid base64');
192+
$this->assertSame($originalContent, $decoded, 'Decoded data should match original content (no double encoding)');
193+
}
194+
171195
/**
172196
* @return void
173197
*/

0 commit comments

Comments
 (0)