I'm simply trying to send a mail with the following code.

function contact_form_mail($key, &$message, $params){
    switch ($key) {
        case 'contact':
            // Set headers etc
            // $message['headers']['Reply-To'] = $params['to'];
            $message['headers']['Content-Type'] = 'text/html';
            $message['headers']['From'] = $params['from'];
            $message['to'] = $params['to'];
            $message['subject'] = $params['subject'];
            $message['body'] = $params['body'];

public function sendForm(){
        $user = $this->getCurrentUser();
        $recipent = $this->findEmailForLocation($this->getLocation());
        if(empty($recipent)){ return; }
        $request = \Drupal::request();
        $subject = $request->get('subject');
        $body = $request->get('body');
        if(empty($subject) || empty($body)){
            return $this->redirect('contact_form.contact', ['error' => 'Fill in all fields.']);
        $mailManager = \Drupal::service('plugin.manager.mail');
            ['[email protected]'],
            ['to' => [$recipent], 'from' => $user->getEmail(), 'subject' => $subject, 'body' => $body],
        return $this->redirect('contact_form.contact', ['success' => 'Data sent']);

I'm getting this error.

Warning: Invalid argument supplied for foreach() in Drupal\Core\Mail\MailManager->doMail() (line 286 of core/lib/Drupal/Core/Mail/MailManager.php).

I have no clue which value is wrong and/or what kind of datatype it should be.

  • 1
    Best thing to do is go look in the code at the error being mentioned (line 286 of core/lib/Drupal/Core/Mail/MailManager.php). That's about the $message['body'] so it's likely your $body = $request->get('body'); isn't an array as it's expecting
    – Leigh
    Commented Jul 21, 2022 at 14:08
  • I don't think you need this line (I've never needed to do this), and it could potentially be the source of your issue: ` ['to' => [$recipent], 'from' => $user->getEmail(), 'subject' => $subject, 'body' => $body],`
    – Jaypan
    Commented Jul 21, 2022 at 17:34
  • @Leigh it took me a while to find out yeah. For some reason they want the body to be an array. Not sure why
    – Coolguy31
    Commented Jul 22, 2022 at 14:13

1 Answer 1


After looking for answers for a while I figured out that body needs to be an array instead of a string. Not sure why. But I changed it, and it directly started working.

  • It's documented in hook_mail(): body: An array of lines containing the message to be sent.
    – apaderno
    Commented Jul 22, 2022 at 14:27
  • Yeah I think I just overlooked it
    – Coolguy31
    Commented Jul 25, 2022 at 7:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.