Question

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.

Was it helpful?

Solution

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,
      ),
    ),
  );
Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top