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
Programming Language: PHP
Add hook to your module
Source code viewer
function HOOK_mail($key, &$message, $params) { switch ($key) { case 'test_attachment': $message['subject'] = $params['subject']; $message['body'][] = $params['body']; $message['params']['attachments'] = $params['attachments']; break; } } Programming Language: PHP
Code to send the email out
Source code viewer
$filepath = 'public://my-file.png'; $to = 'MAILTO@gmail.com'; return drupal_set_message('File not found: ' . $filepath, 'error'); } // Get real file path for debug $file_mime = file_get_mimetype($filepath); $params = [ 'subject' => 'My test email', 'body' => 'My test email with attachment.', 'attachments' => [ [ 'filename' => 'my-file.png', 'filemime' => $file_mime, ], ], ]; $langcode = language_default(); $send = TRUE; $result = drupal_mail('HOOK', 'test_attachment', $to, $langcode, $params, NULL, $send); if ($result['result']) { drupal_set_message('Email sent successfully with attachment.'); } else { drupal_set_message('Email failed to send.', 'error'); }Programming Language: PHP