Normally we send files as attachments in the email if they are stored in the file system.

$file->uri = 'sites/default/files/file_name.pdf'; // File path
$file->filename = 'file_name.pdf'; //File name
$file->filemime = 'application/pdf'; //File mime type
$params['attachments'][] = $file;
$mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);

But I have dynamically generated content.

$content = <?xml version="1.0"?>
<root><element>element value</element></root>

I want to send it as an XML file attachment in the email. How can I do this?

1 Answer 1


I have found the answer.

Here is my code.

$content = '<?xml version="1.0"?><root><element>element value</element</root>';
$params['attachments'][] = [
  'filecontent' => $content,
  'filename' => 'data.xml',
  'filemime' => 'application/xml',

and then in hook_mail

function mymodule_mail($key, &$message, $params) {
  switch ($key) {
    case 'my_email_key':
      $message['body'][] = $params['body'];
      $message['subject'] = $params['subject'];
      $message['params']['attachments'] = $params['attachments'];

BTW I am using the swift mailer module.

Hope this helps someone.

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.