How to send dynamic content as an attachment file in email?
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.