When sending an email with a pdf attachment you get the following errors:

Warning: realpath() expects parameter 1 to be a valid path, string given in Drupal\Core\File\FileSystem->realpath() (line 129 of core/lib/Drupal/Core/File/FileSystem.php).

Warning: is_file() expects parameter 1 to be a valid path, string given in Drupal\mimemail\Utility\MimeMailFormatHelper::mimeMailMultipartBody() (line 474 of modules/contrib/mimemail/src/Utility/MimeMailFormatHelper.php).

Issue fork mimemail-2904611

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

janehollander created an issue. See original summary.

janehollander’s picture

StatusFileSize
new18.7 KB

Here's a patch which fixes those error messages that are displayed.

janehollander’s picture

Status: Active » Needs review
blake.thompson’s picture

The patch in #2 worked for me, but there are a lot of fixes related to coding standards rather than this specific issue. Does it make more sense to create a separate issue for those changes? It was hard to decipher the changes related to just this bug.

tr’s picture

Version: 8.x-1.0-alpha2 » 8.x-1.x-dev
StatusFileSize
new2.05 KB

Yes, this patch is MOSTLY coding standards fixes. And many of them are WRONG fixes which introduce new coding standards violations. This is really not the place to go back and forth about coding standards issues. Now that this module is using the testbot (see #2985803: Turn on testing for 8.x-1.x!) we can see and correct coding standards violations in separate patches.

So I've removed all the coding standards changes that were included in the patch from #2 and re-rolled it with just the functional changes related to this issue.

I must say that I don't think suppressing errors using @is_file is the right solution to this problem. Hiding the error doesn't actually fix anything ...

guerinteed_mike’s picture

+ 1 Following

I am experiencing same issue.

There is not a whole lot of documentation on this issue. Is it possible to create test module?

thanks for the great module!!

tr’s picture

@guerinteed_mike: Did you have the same issue? Did the patch fix it?

You don't need to post just to follow the issue - instead, click on the "Follow" link next to the star in the block in the upper right of this page.

guerinteed_mike’s picture

@TR

Thank you for response. I will give it a shot within the next few days and let you know the turn out.

mikeg

tr’s picture

@guerinteed_mike: Did the patch work for you?

guerinteed_mike’s picture

@TR - I wanted to let you know this is still on my radar. Have not yet tried patch but will plan to get it to it next week

derekrezek’s picture

same issue, i think patch #5 Should Fix the issue.

when a user creates an attachment in the format, e.g. :

//please note uri is missing here:
        $params['files'][] = array(
          'filecontent' => $dompdf->output(), //file content pumped in 
          'filename' => $pdffilename . '.pdf',
          'filemime' => 'application/pdf'
        );

what is happening is :

     if (isset($file) && (@is_file($file) || $content)) {
       $public_path = \Drupal::config('system.file')->get('default_scheme') . '://';
       $no_access = !\Drupal::currentUser()->hasPermission('send arbitrary files');
       $not_in_public_path = strpos(\Drupal::service('file_system')->realpath($file), \Drupal::service('file_system')->realpath($public_path)) !== 0;//this line is still checking for realpath on $file even though it has entered the if condition with only the $content set.
tr’s picture

StatusFileSize
new2.04 KB

Here's a re-roll of #5 to apply to the current HEAD.

imclean’s picture

Attaching files can be done by either passing the path to the file or passing the file contents directly. The issue summary doesn't state which method was used, although I suspect it's the latter. #11 refers to this method.

The code handling file attachments is a bit messy and tries to use the single variable $file to hold either a URL or the file contents, which it then strangely checks even though it will always be set. See:

  if ($url) {
    // ...
  }
  // We have the actual content.
  elseif ($content) {
    $file = $content;
  }

  if (isset($file) && (@is_file($file) || $content)) {
    // ...
  }

A better idea would be to treat $file and $content as separate exclusive options. This could involve a a more comprehensive refactoring, but for a quick demonstration here's an alternate method of handling file content attachments.

imclean’s picture

StatusFileSize
new1.78 KB

Minor tidy up.

aiphes’s picture

Hi,

I would apply this patch to get working emails with attachment via webform.
But I get an error message about outdated patch with the #14 version.
https://www.drupal.org/project/mimemail/issues/3127506

DFO I need to use another patch ? which one ?

If someone can help me.

Thanks

tr’s picture

@aiphes: I answered your question in #3127506-7: Mimemail and Webform : attachment. The patch is good. You can verify that by looking at the testbot output in #14 where you'll see I re-triggered the test yesterday and verified the patch was good. I already told you this. The patch applies with git and with patch. This is not the place to get help with using some third-party development tool.

sgabe’s picture

@aiphes: There is a "Version control" tab on the project page that provides basic instructions on how to use Git, please follow those when working with Drupal project source files.

aiphes’s picture

Thanks all, seem Tortoise isn't the right tool, will try with git command line (hope it do on windows machine)

tr’s picture

Status: Needs review » Postponed (maintainer needs more info)

I am using Mime Mail for both the formatter and sender.

I tested PDF attachments with the new mimemail_example module (you will need the latest mimemail -dev for this). If you install this module then go to example/mimemail_example and fill out the form, you can send a test e-mail with an attachment. This worked for me for attaching PDF files. No errors were generated in the log, and I received a properly formatted e-mail and was able to open the attachment and view the PDF file in my mail client.

The mimemail_example module passes the file path, and only the file path, to the helper function. Specifically, in MimeMailFormatHelper.php::mimeMailHtmlBody() line 142, the $attachments array contains:
array( 0 => array ( 'filepath' => 'public://my_file.pdf', ), )

As described by @imclean in #13, this is does not seem to be the way the error is triggered. Instead, it is triggered by passing in the file contents instead of the file path. I don't currently have a way to test that 'contents' method so I don't have a way to verify the bug and I don't have a way to see if #14 fixes the bug.

It would be great if someone would contribute some test code or better yet a test case to demonstrate this bug. That way we can fix it and have the test case to prove it is fixed ...

Likewise, if we had a test case, we could test that this works for both public and private files, embedded images, etc. As @imclean said in #13 the code is very messy and needs to be refactored, but I don't want to do that unless we have test cases to prove it's doing the right thing.

I think Kernel tests for all the MimeMailFormatHelper functions are badly needed.

imclean’s picture

Here's a quick overview of how we're using MIME Mail to send attachments.

Website content is created by the website owner (via REST, but can be manual). This includes a "Permit" content type which can have multiple documents attached as media entities. These documents are PDFs and are stored in the "private" file system to prevent direct access.

A customer can then purchase a permit. After payment, the relevant PDFs are emailed to the customer. This is done by loading the media entities then the file entities reference by the media entities.

The use of the private file system may have been the issue here.

This is an example of the type of code we're using.

Custom service:

  public function sendEmails($mids, $email) {
    $attachments = [];
    // Load the media entities and referenced file entities.
    foreach ($mids as $mid) {
      $media_entity = $this->entityTypeManager->getStorage('media')->load($mid['target_id']);
      $fid = $media_entity->get('field_media_file')->first()->getValue()['target_id'];
      $file_entity = $this->entityTypeManager->getStorage('file')->load($fid);

      $attachments[] = [
        'filecontent' => file_get_contents($file_entity->getFileUri()),
        'filename' => $file_entity->getFilename(),
        'filemime' => $file_entity->getMimeType(),
      ];
    }

    // Load config.
    $config = $this->getPermitConfig();

    // Get email content.
    $subject = $config->get('email_subject');
    $body = $config->get('email_body');

    // Set up the parameters for the email.
    $params = [
      'subject' => $subject,
      'body' => $body,
      'attachments' => $attachments,
    ];

    // Send the email.
    return $this->mailManager->mail('my_module', 'my_module', $email, null, $params, TRUE);
  }

my_module.module:

/**
 * Implements hook_mail().
 * 
 * @param type $key
 * @param type $message
 * @param type $params
 */
function my_module_mail($key, &$message, $params) {
  switch ($key) {
    case 'my_module':
      $message['subject'] = $params['subject'];
      $message['body'][] = $params['body'];
      $message['headers']['Content-Type'] = 'text/html; charset=utf-8';
      $message['params']['attachments'] = $params['attachments'];      
      break;
  }
}
imclean’s picture

I'll have a look at the example module to see if we can do something there.

imclean’s picture

Status: Postponed (maintainer needs more info) » Active

I see you've changed the file handling a bit. I've updated the example module locally and it can handle attaching private files using the scheme private://.

I can also add an example of using the contents of a file to add an attachment. @TR, is this something you'd support?

tr’s picture

Sure. I think the whole purpose of the mimemail_example module is to provide something useful for testing, debugging, and documenting - not only for site builders who are trying to integrate Mime Mail but also for development of Mime Mail, to test features and demonstrate bugs. Plus, it should serve as an example of how to use Mime Mail programmatically. I've already started using it to try to debug / reproduce issues in the issue queue, like this one, and to investigate support questions, and I think it's going to be very useful for people trying to get Mime Mail working on their own.

So anything you can contribute that will make it more useful would be appreciated. You can open new issues for each new feature, that way we can keep new features separate from bug reports and make sure you get credit for your contributions.

imclean’s picture

The related issue demonstrates the problem seen here.

imclean’s picture

Double post.

imclean’s picture

Status: Active » Needs review

This is still an issue. We're using the patch in #14. The problem can be demonstrated by the patch in #24 (which may need a re-roll).

What else needs to be done here?

imclean’s picture

Sorry, I meant the problem can be demonstrated by the issue linked to in 24: #3129469: Support adding attachments as file contents

tr’s picture

Well, the bottleneck is me, but it's on my radar so it will get fixed ...

This issue IS a problem and the patch DOES prevent it, but this code is still really messed up and needs bigger fixes. We keep running into the same problems then slapping quick fixes on them, and the code becomes more and more of a patchwork that isn't documented, tries to do too much, and is still full of bugs. Take this issue as an example - we had the same problem in D7 (#2366659: Attachments created using 'content' instead of 'file' generate warnings) and the same problem in (#1850262: Sending content based mimemails), and we're still no closer making this code work properly. I really don't want to make another quick fix and hide an error.

What I want to do is rewrite mimeMailFile(), but before I do that I need to ensure I'm not just trading one set of known problems that we have now for a new set of unknown problems with the rewrite. The way to do that is to have tests. But before the tests I need to understand what the code is *supposed* to do, and that's a problem with everything in MimeMailFormatHelper (which should really be a service rather than random static functions, BTW, but that's another issue entirely).

Looking at mimeMailFile(), the function name has nothing to do with its actual operation, it's documented as a "Helper function" but what "help" does it provide? It returns "The Content-ID and/or an array of the files on success or the URL on failure." - so that's a string, OR an array with an undocumented structure, OR a different string containing a URL. What? All the arguments are optional AND you have to call the function twice (ignoring the return value the first time, passing NO arguments the second time) for it to work properly?

  foreach ($attachments as $a) {
    ...
    static::mimeMailFile($path, $content, $name, $type, 'attachment');
    $parts = array_merge($parts, static::mimeMailFile());
  }

"@is_file" is used FOUR times in mimeMailFile(), suppressing the error message each time means we've avoided seeing this problem or other related problems - instead we just hide them away until someone comes along with a slightly different case that exposes the problem again. This function uses mimeMailUrl() which is ALSO a "Helper function" with no documentation about what it does, so we don't know if that is doing the right thing or not (BTW, it's NOT doing the right thing currently either ...)

I really can't support or maintain this piece of ... code without robust test cases. I've started doing that, and I've opened up a bunch of issues (e.g. #3145400: Add test cases for MimeMailFormatHelper::mimeMailFile()) and I'm slowly working my way through this. Since mimeMailFile() uses mimeMailUrl(), I'd like to get mimeMailUrl() tested and fixed first because mimeMailFile() won't work properly without it.

In my local copy of MimeMailFormatHelper I have added a lot of documentation and general structural fixes, and I need to start pushing more of that out. But the big blocker is the tests - we need to get away from patching things without tests and we need to start having tests for everything - this has been Drupal core policy for like 10 years now.

The only thing you can do to speed up the process is to try to write some of the tests - for mimeMailUrl() for example, or for mimeMailFile(). I already have a lot of the rewrite done and will be making a bunch of small changes that fix the structure and specifically avoid the problem in this issue, but I don't have the tests yet and they tend to take a while to write even when the code is working, let alone when it's broken ...

tr’s picture

@imclean said:

The code handling file attachments is a bit messy and tries to use the single variable $file to hold either a URL or the file contents, which it then strangely checks even though it will always be set.

Here are 17 issues over the years caused by this mess:
https://www.drupal.org/project/issues/mimemail?text=is_file&status=All&p...

This is why I want to fix this function, not just patch it.

I spent a few hours last night experimenting with this (giving mimeMailFile() input to see what it does), and I found even more problems which go back to Drupal 6 and have never been noticed before. I will be posting new issues and hopefully some tests for mimeMailFile() in the next few days.

imclean’s picture

@TR,

I really don't want to make another quick fix and hide an error.

This is why I took the approach I did in #14. But as you say, the entire "helper" needs rewriting. I'm still no closer to understanding the flow when attaching files, I just fixed an error where it occurred.

aiphes’s picture

Applying patch #14 on fresh D8.9.13 install fix the warning :)
wget -q -O - https://www.drupal.org/files/issues/2020-02-04/mimemail_attachment_errors-2904611-14_0.patch | git apply in the module folder.

mchamps’s picture

Hi,
I'm running Drupal 9.3.3 and mimemail 8.x-1.0-alpha4
I have a similar error when sending and email with a PDF attachement from Webmail.

ValueError : realpath(): Argument #1 ($path) must not contain any null bytes dans realpath() (v2-1/web/core/lib/Drupal/Core/File/FileSystem.php ligne 139)
#0 v2-1/web/core/lib/Drupal/Core/File/FileSystem.php(139): realpath('%PDF-1.7\n1 0 ob...')
#1 v2-1/web/modules/contrib/mimemail/src/Utility/MimeMailFormatHelper.php(395): Drupal\Core\File\FileSystem->realpath('%PDF-1.7\n1 0 ob...')
#2 v2-1/web/modules/contrib/mimemail/src/Utility/MimeMailFormatHelper.php(216): Drupal\mimemail\Utility\MimeMailFormatHelper::mimeMailFile(NULL, '%PDF-1.7\n1 0 ob...', '22-05-17 DUFOUR...', 'application/pdf', 'attachment')
#3 v2-1/web/modules/contrib/mimemail/src/Plugin/Mail/MimeMail.php(206): Drupal\mimemail\Utility\MimeMailFormatHelper::mimeMailHtmlBody('<!DOCTYPE HTML ...', 'Contrat de loca...', false, '\xC2\xA0Bonjour Mme D...', Array)
#4 v2-1/web/modules/contrib/mimemail/src/Plugin/Mail/MimeMail.php(105): Drupal\mimemail\Plugin\Mail\MimeMail->prepareMessage(Array)
#5 v2-1/web/modules/contrib/mailsystem/src/Adapter.php(43): Drupal\mimemail\Plugin\Mail\MimeMail->format(Array)
#6 v2-1/web/core/lib/Drupal/Core/Mail/MailManager.php(293): Drupal\mailsystem\Adapter->format(Array)
#7 v2-1/web/core/lib/Drupal/Core/Mail/MailManager.php(180): Drupal\Core\Mail\MailManager->doMail('webform', 'reservation_for...', 'dufour.aurelie@...', 'fr', Array, '=?UTF-8?B?R8Oud...', true)
#8 v2-1/web/core/lib/Drupal/Core/Render/Renderer.php(564): Drupal\Core\Mail\MailManager->Drupal\Core\Mail\{closure}()
#9 v2-1/web/core/lib/Drupal/Core/Mail/MailManager.php(181): Drupal\Core\Render\Renderer->executeInRenderContext(Object(Drupal\Core\Render\RenderContext), Object(Closure))
#10 v2-1/web/modules/contrib/mailsystem/src/MailsystemManager.php(70): Drupal\Core\Mail\MailManager->mail('webform', 'reservation_for...', 'dufour.aurelie@...', 'fr', Array, '=?UTF-8?B?R8Oud...', true)
#11 v2-1/web/modules/contrib/webform/src/Plugin/WebformHandler/EmailWebformHandler.php(1207): Drupal\mailsystem\MailsystemManager->mail('webform', 'reservation_for...', 'dufour.aurelie@...', 'fr', Array, '=?UTF-8?B?R8Oud...')
#12 v2-1/web/modules/contrib/webform/src/Form/WebformSubmissionResendForm.php(162): Drupal\webform\Plugin\WebformHandler\EmailWebformHandler->sendMessage(Object(Drupal\webform\Entity\WebformSubmission), Array)
#13 [internal function]: Drupal\webform\Form\WebformSubmissionResendForm->submitForm(Array, Object(Drupal\Core\Form\FormState))
#14 v2-1/web/core/lib/Drupal/Core/Form/FormSubmitter.php(114): call_user_func_array(Array, Array)
#15 v2-1/web/core/lib/Drupal/Core/Form/FormSubmitter.php(52): Drupal\Core\Form\FormSubmitter->executeSubmitHandlers(Array, Object(Drupal\Core\Form\FormState))
#16 v2-1/web/core/lib/Drupal/Core/Form/FormBuilder.php(592): Drupal\Core\Form\FormSubmitter->doSubmitForm(Array, Object(Drupal\Core\Form\FormState))
#17 v2-1/web/core/lib/Drupal/Core/Form/FormBuilder.php(320): Drupal\Core\Form\FormBuilder->processForm('webform_submiss...', Array, Object(Drupal\Core\Form\FormState))
#18 v2-1/web/core/lib/Drupal/Core/Controller/FormController.php(73): Drupal\Core\Form\FormBuilder->buildForm(Object(Drupal\webform\Form\WebformSubmissionResendForm), Object(Drupal\Core\Form\FormState))
#19 [internal function]: Drupal\Core\Controller\FormController->getContentResult(Object(Symfony\Component\HttpFoundation\Request), Object(Drupal\Core\Routing\RouteMatch))
#20 v2-1/web/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(123): call_user_func_array(Array, Array)
#21 v2-1/web/core/lib/Drupal/Core/Render/Renderer.php(564): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
#22 v2-1/web/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(124): Drupal\Core\Render\Renderer->executeInRenderContext(Object(Drupal\Core\Render\RenderContext), Object(Closure))
#23 v2-1/web/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(97): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array)
#24 v2-1/vendor/symfony/http-kernel/HttpKernel.php(158): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
#25 v2-1/vendor/symfony/http-kernel/HttpKernel.php(80): Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1)
#26 v2-1/web/core/lib/Drupal/Core/StackMiddleware/Session.php(58): Symfony\Component\HttpKernel\HttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#27 v2-1/web/core/lib/Drupal/Core/StackMiddleware/KernelPreHandle.php(48): Drupal\Core\StackMiddleware\Session->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#28 v2-1/web/core/modules/page_cache/src/StackMiddleware/PageCache.php(106): Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#29 v2-1/web/core/modules/page_cache/src/StackMiddleware/PageCache.php(85): Drupal\page_cache\StackMiddleware\PageCache->pass(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#30 v2-1/web/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(48): Drupal\page_cache\StackMiddleware\PageCache->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#31 v2-1/web/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(51): Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#32 v2-1/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#33 v2-1/web/core/lib/Drupal/Core/DrupalKernel.php(708): Stack\StackedHttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#34 v2-1/web/index.php(19): Drupal\Core\DrupalKernel->handle(Object(Symfony\Component\HttpFoundation\Request))
#35 {main}

When I try to apply the patch with composer I get :

Could not apply patch! Skipping. The error was: Cannot apply patch https://www.drupal.org/files/issues/2019-04-27/2904611-12.patch

I also tried aiphes #31's method wget -q -O - https://www.drupal.org/files/issues/2020-02-04/mimemail_attachment_errors-2904611-14_0.patch | git apply
and get

Could not apply patch! Skipping. The error was: Cannot apply patch https://www.drupal.org/files/issues/2020-02-04/mimemail_attachment_error...

I also tried with mimemail.dev and have the same errors.

I did not have this error with Drupal 8.9.19
Cheers

dbroll’s picture

I'm running Drupal 8.9.16 and mimemail 8.x-1.0-alpha4 (also tried the dev version)
I am getting both of the original errors, I tried patch 14 but it fails to apply.

dpi made their first commit to this issue’s fork.

dpi’s picture

Rebased/resolved conflicts as MR.

dpi’s picture

Title: Seeing errors when sending a mail with pdf attached » Seeing errors when sending a mail with large files attached

I dont have this issues with PDF's, rather large files with specifically unrecognised characters are causing issues for \realpath(), same as #32.

imclean’s picture

Title: Seeing errors when sending a mail with large files attached » Seeing errors when sending a mail with files attached as file contents

#32 and #37 is a separate issue. Let's keep this one focussed with a more accurate title.

The problem is Mime Mail using the same variable for either a file path or file contents. The errors occur when passing the file contents to realpath() and is_file(). The error should not be hidden, instead the situation shouldn't arise in the first place.

trakoczi’s picture

Since we would like to stick to alpha4 for now and switch to the dev branch, I have prepared the patch file for alpha4, in case anyone else needs it too.

tjtj’s picture

The patch 39 does not fully apply on D9
patch -p1 < mimemail_attachment_errors-2904611-39.patch
patching file src/Utility/MimeMailFormatHelper.php
Hunk #1 succeeded at 5 with fuzz 2.
Hunk #2 FAILED at 393.
Hunk #3 FAILED at 417.
Hunk #4 succeeded at 649 with fuzz 2 (offset 3 lines).
2 out of 4 hunks FAILED -- saving rejects to file src/Utility/MimeMailFormatHelper.php.rej

tr’s picture

Issue tags: +Needs tests

@tjtj: No, you're wrong. As you can see, I triggered a re-test of the patch in #39 and the patch applies without a problem.

Of course, this patch still doesn't have any tests, so you can't tell whether it actually fixes anything, but the patch DOES apply.

The problem must be on your end - you may have an old version of this module, or you may have made local changes to the module code that conflict with the patch.

tjtj’s picture

I get in the reject file

cat src/Utility/MimeMailFormatHelper.php.rej
--- src/Utility/MimeMailFormatHelper.php
+++ src/Utility/MimeMailFormatHelper.php
@@ -393,7 +394,13 @@
     if (isset($file) && (@is_file($file) || $content)) {
       $public_path = $file_config->get('default_scheme') . '://';
       $no_access = !$current_user->hasPermission('send arbitrary files');
-      $not_in_public_path = mb_strpos($file_system->realpath($file), $file_system->realpath($public_path)) !== 0;
+      if (!$content) {
+        $not_in_public_path = mb_strpos($file_system->realpath($file), $file_system->realpath($public_path)) !== 0;
+      }
+      else {
+        $not_in_public_path = TRUE;
+      }
+
       if (@is_file($file) && $not_in_public_path && $no_access) {
         return $url;
       }
@@ -417,11 +424,17 @@
         // Store the metadata in our static $files array indexed by $id.
         $files[$id] = [
           'name' => $name,
-          'file' => $file,
           'Content-ID' => $id,
           'Content-Disposition' => $disposition,
           'Content-Type' => $type,
         ];
+
+        if ($content) {
+          $files[$id]['filecontent'] = $content;
+        }
+        else {
+          $files[$id]['file'] = $file;
+        }
       }

       // Return the content id for this item.

In my file, I have

    if (isset($file) && (@is_file($file) || $content)) {
      $public_path = \Drupal::config('system.file')->get('default_scheme') . '://';
      $no_access = !\Drupal::currentUser()->hasPermission('send arbitrary files');
      $not_in_public_path = mb_strpos(\Drupal::service('file_system')->realpath($file), \Drupal::service('file_system')->realpath($public_path)) !== 0;
      if (@is_file($file) && $not_in_public_path && $no_access) {
        return $url;
      }

The patch does not have Drupal::config(. I downloaded the module today.
I will now try the dev version... YES, it worked.

mmmbsmm’s picture

Has anyone figured

The website encountered an unexpected error. Please try again later.
ValueError: realpath(): Argument #1 ($path) must not contain any null bytes in realpath() (line 139 of core/lib/Drupal/Core/File/FileSystem.php).

yet? I am using mimemail and phpmailer smtp to send the attachment when you submit a webform but I am continuously getting this error. My test mail is sent to me successfully but it just wouldn't work in webform.

imclean’s picture

For #32, #37 and #43, I've opened #3271547: Seeing errors when sending a mail with large files attached.

@mchamps, @dpi and/or @mmmbsmm could you please fill in some details in the issue summary. Specifically how to reproduce would be helpful.

imclean’s picture

rdworianyn’s picture

This doesn't resolve the issue, but I did find that a quick workaround is to instead output the file to a path, such as /tmp/myfile.pdf, and then use the following:

$file_name = "SomeFileName".pdf";
$path = '/tmp/' . $file_name;
$mpdf->Output($path, 'F');

$attachments[] = [
        'filepath' => $path,
        'filename' => $file_name,
        'filemime' => 'application/pdf',
];

I just tested this using Drupal 9.4.0, Mime Mailer as the Formatter, and SMTP Mailer as the Sender, under the Mail System Module.

aiphes’s picture

Still there with D9.4.8 + Mime Mail 8.x-1.0-alpha4
ValueError : realpath(): Argument #1 ($path) must not contain any null bytes dans realpath() (/home/xx-xx/www/xxx/sited9/web/core/lib/Drupal/Core/File/FileSystem.php ligne 139)

sic’s picture

Come ooooooon

gaurav-mathur’s picture

Status: Needs review » Needs work

I don't know how they are installing this module. The module is not compatible with D9 and D10 and patch #39 is not applied on drupal 9.4.x.I think this move need to be work .

tr’s picture

Status: Needs work » Needs review

I don't know how they are installing this module. The module is not compatible with D9 and D10

This module absolutely IS compatible with Drupal 9. And it HAS been compatible with Drupal 9 for more than two years - since even before the official release of D9.

This module makes no claims that it is compatible with the brand-new release of Drupal 10 yet. If you want that to happen you can contribute here in the issue queue and help fix the known problems.

And again, I just retriggered the test in #39 and as you can see the testbot has absolutely no problem applying the patch. There is nothing wrong with the patch, the problem is on your end.

If you're interested in fixing this issue, then I think I've been pretty clear that there needs to be tests for this functionality. You can help.

aiphes’s picture

Hi,
As in #47, I still get this error with WSOD. v 8.x-1.0-alpha4

The website encountered an unexpected error. Please try again later.
ValueError: realpath(): Argument #1 ($path) must not contain any null bytes in realpath() (line 139 of core/lib/Drupal/Core/File/FileSystem.php).
realpath('') (Line: 139)
Drupal\Core\File\FileSystem->realpath('') (Line: 395)
Drupal\mimemail\Utility\MimeMailFormatHelper::mimeMailFile(NULL, '', 'google_analytics_audience-_-_brise-lames.pdf', 'application/pdf', 'attachment') (Line: 216)
Drupal\mimemail\Utility\MimeMailFormatHelper::mimeMailHtmlBody('
    Mime Mail message template
        test envoi pj
', 'Poste recherché dans le domaine [webform_submission:webform:element:poste_recherche:raw]', , 'test envoi pj
', Array) (Line: 206)
Drupal\mimemail\Plugin\Mail\MimeMail->prepareMessage(Array) (Line: 105)
Drupal\mimemail\Plugin\Mail\MimeMail->format(Array) (Line: 43)
Drupal\mailsystem\Adapter->format(Array) (Line: 289)

Do I need to patch the module or something else ?
Thanks

EDIT: patch doesn't fix the issue, will try with dev version
EDIT2: bad

  Problem 1
    - Root composer.json requires drupal/mimemail 1.x-dev, found drupal/mimemail[dev-1.x, 1.x-dev (alias of dev-1.x)] but it does not match your minimum-stability.

my composer file:

 "minimum-stability": "dev",
    "prefer-stable": true,

:/ weird ?

qqboy’s picture

locally, if I use

$params['attachments'][] = [
'filepath' => $file->getFileUri(),
];

avoided this patch, since this patch is stilled not imported to Module itself in alph-4.

mably’s picture

Patch #39 doesn't work with latest alpha5 :(

mably’s picture

Tried to port #39 patch to alpha5 source code. Seems to work, not heavily tested though.

_tarik_’s picture

#55 +1 worked for me, PHP 8.1.16 - D9.5.8

kris77’s picture

#55 +1 worked for me to with latest alpha5.

Thanks @mably.

RyanCMcConnell’s picture

#55 worked for me as well. Thank you @mably !

sinn’s picture

Status: Needs review » Reviewed & tested by the community

#55 works well

kris77’s picture

#55 works for me too.
Thanks @mably

Bagz’s picture

#55 works with alpha6 on Drupal 10.2.3 with PHP 8.2.16

betarobot’s picture

#55 worked well with PHP 8.2.17 and Drupal 10.2.5.

heni_deepak’s picture

#55 Work well with PHP 8.3.21 and Drupal 10.4.5
Thanks @mably

  • mark_fullmer committed 5633181c on 2.0.x
    [#2904611] bug: Seeing errors when sending a mail with files attached as...
mark_fullmer’s picture

Status: Reviewed & tested by the community » Fixed

Thanks everyone, for the implementation, and for the reviews above. This has been merged.

Now that this issue is closed, please review the contribution record.

As a contributor, attribute any organization that helped you, or if you volunteered your own time.

Maintainers, please credit people who helped resolve this issue.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.