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', 'my_own_mail@gmail.com', $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

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', 'my_own_mail@gmail.com', $language, $params);

}

Update:

to send attachement you need just the filePath try with:

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

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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