15 April 2025

To send emails with attachments in Drupal 7, you need to install and configure the SMTP module, then enable it as the default mail system using variable_set. After that, implement hook_mail() in your custom module to define the message structure. Once everything is set up, you can send emails from your code using drupal_mail(), and include attachments by adding them to the $message['params']['attachments'] array.

Set mailsystem to SMTP

Source code viewer
  1. variable_set('mail_system', array('default-system' => 'SmtpMailSystem'));
Programming Language: PHP

Add hook to your module

Source code viewer
  1. function HOOK_mail($key, &$message, $params) {
  2. switch ($key) {
  3. case 'test_attachment':
  4. $message['subject'] = $params['subject'];
  5. $message['body'][] = $params['body'];
  6. $message['params']['attachments'] = $params['attachments'];
  7. break;
  8. }
  9. }
  10.  
Programming Language: PHP

Code to send the email out

Source code viewer
  1. $filepath = 'public://my-file.png';
  2. $to = 'MAILTO@gmail.com';
  3.  
  4. if (!file_exists($filepath)) {
  5. return drupal_set_message('File not found: ' . $filepath, 'error');
  6. }
  7.  
  8. // Get real file path for debug
  9. $real_path = realpath($filepath);
  10. $file_mime = file_get_mimetype($filepath);
  11.  
  12. $params = [
  13. 'subject' => 'My test email',
  14. 'body' => 'My test email with attachment.',
  15. 'attachments' => [
  16. [
  17. 'filecontent' => file_get_contents($filepath),
  18. 'filename' => 'my-file.png',
  19. 'filemime' => $file_mime,
  20. ],
  21. ],
  22. ];
  23. $langcode = language_default();
  24. $send = TRUE;
  25.  
  26. $result = drupal_mail('HOOK', 'test_attachment', $to, $langcode, $params, NULL, $send);
  27.  
  28. if ($result['result']) {
  29. drupal_set_message('Email sent successfully with attachment.');
  30. }
  31. else {
  32. drupal_set_message('Email failed to send.', 'error');
  33. }
Programming Language: PHP