How to send dynamic content as an attachment file in email? Normally we send files as attachments in the email if they are stored in the file system.
$file-&gt;uri = 'sites/default/files/file_name.pdf'; // File path
$file-&gt;filename = 'file_name.pdf'; //File name
$file-&gt;filemime = 'application/pdf'; //File mime type
$params['attachments'][] = $file;
$mailManager-&gt;mail($module, $key, $to, $langcode, $params, NULL, $send);

But I have dynamically generated content.
$content = &lt;?xml version=&quot;1.0&quot;?&gt;
&lt;root&gt;&lt;element&gt;element value&lt;/element&gt;&lt;/root&gt;

I want to send it as an XML file attachment in the email. How can I do this?
I have found the answer.
Here is my code.
$content = '&lt;?xml version=&quot;1.0&quot;?&gt;&lt;root&gt;&lt;element&gt;element value&lt;/element&lt;/root&gt;';
$params['attachments'][] = [
  'filecontent' =&gt; $content,
  'filename' =&gt; 'data.xml',
  'filemime' =&gt; 'application/xml',
];

and then in hook_mail
function mymodule_mail($key, &amp;$message, $params) {
  switch ($key) {
    case 'my_email_key':
      $message['body'][] = $params['body'];
      $message['subject'] = $params['subject'];
      $message['params']['attachments'] = $params['attachments'];
      break;
  }
}

BTW I am using the swift mailer module.
Hope this helps someone.