1

I'm working on a form submit in a Drupal 7 project, the form has and upload file field, in my form submit handler I can get the file id, what I want to do is to send and mail which has as attachment the uploaded file.

my form submit function:

function my_form_submit($form, &$form_state) {
  $fid = $form_state['values']['document'];
  $file = file_load($fid);
  $params = array(
    'attachment' => $file,
  );
  global $language;
    drupal_mail('my_module', 'key_1', '[email protected]', $language, $params);

}

hook_mail implementation:

function my_module_mail($key, &$message, $params){
  switch ($key) {
    case 'key_1':
      $message['subject'] = t('my mail subject');
      $message['body'][] = t('Hello this is a test content');
      $message['params']['attachments'][] = $params['attachment'];
  }
}

When submitting the form the mail has not been sent and this error is shown:

Error : Cannot use object of type stdClass as array in my_module_mail()

Anybody has an idea why it doesn't accept object and or how to deal with this in this case. Thanks.

1 Answer 1

1

file_load return file object:

Loads a single file object from the database.

But $message['params']['attachments'][] should be an array.
So just change $file = file_load($fid); to $file = (array)file_load($fid); in your submit function my_form_submit will be like:

function my_form_submit($form, &$form_state) {
  $fid = $form_state['values']['document'];
  //file object as an array. 
  $file = (array)file_load($fid);
  $params = array(
    'attachment' => $file,
  );
  global $language;
    drupal_mail('my_module', 'key_1', '[email protected]', $language, $params);

}

Update:

to send attachement you need just the filePath try with:

$params = array(
    'attachments' => array(
      0 => array(
        'filepath' => $file->uri,
      ),
    ),
  );
3
  • yes I've already test it the error message disappeared but on mail delivery there is no attachments.
    – MiharbKH
    Commented Dec 26, 2018 at 23:15
  • 1
    yeah i had that issue, check the update. and tell me if its works.
    – berramou
    Commented Dec 26, 2018 at 23:25
  • i'm glad that help, you are so welcome man.
    – berramou
    Commented Dec 26, 2018 at 23:39

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.