How to get the URL of an entity being created at hook_entity_insert() stage? I'm trying to send an email "someone added content" with the URL to the entity as the message body.

function MYMODULE_entity_insert(EntityInterface $entity) {
  if ($entity-&gt;getEntityTypeId() === 'node') {
    switch ($entity-&gt;bundle()) {
      case 'contact':
        MYMODULE_mail_notify_admin($entity);
    }
  }
}

function MYMODULE_mail_notify_admin($entity) {
  $mailManager = \Drupal::service('plugin.manager.mail');
  $module = 'MYMODULE';
  $key = 'contact';
  $to = 'secret@secret.com';
  # $to = \Drupal::currentUser()-&gt;getEmail();
  $params['message'] = $entity-&gt;toUrl()-&gt;getUri();
  $params['title'] = $entity-&gt;label;
  $langcode = \Drupal::currentUser()-&gt;getPreferredLangcode();
  $send = true;


The problem is that $entity-&gt;toUrl()-&gt;getUri() gives an error, "This URL has a Drupal route, so the canonical form is not a URI".

How do I get the URL from a URL object?  Is this a problem because the entity hasn't been created yet, and the route hasn't been assigned?
The URL object is there, you're just calling it wrong.

The code for this is a little complicated:

  $path = $entity-&gt;toUrl('canonical', ['absolute' =&gt; TRUE])-&gt;toString();
  $params['message'] = $path;


For more info, see this issue.