12

Does anyone know how to use the l() or url() function to create mailto links?

I am running drupal 6.

googletorp
  • 33,075
  • 15
  • 67
  • 82
Brian G
  • 53,704
  • 58
  • 125
  • 140

5 Answers5

36

You need to use the absolute option:

l('Mail me', 'mailto:jim@hotmail.com', array('absolute' => TRUE));

will generate

<a href="mailto:jim@hotmail.com">Mail Me</a>
googletorp
  • 33,075
  • 15
  • 67
  • 82
2

A good practice is to use the t() function with strings. Code should be then:

l(t('Mail me'), 'mailto:jim@hotmail.com', array('absolute' => TRUE));
anou
  • 260
  • 2
  • 6
1

Drupal 9 solution

Drupal core has this code in Drupal\Core\Field\Plugin\Field\FieldFormatter\MailToFormatter:

      $elements[$delta] = [
        '#type' => 'link',
        '#title' => $item->value,
        '#url' => Url::fromUri('mailto:' . $item->value),
      ];

So you can create a render array like so:

[
  '#type' => 'link',
  '#title' => $email,
  '#url' => Url::fromUri('mailto:' . $email),
];

Or like this:

Link::fromTextAndUrl($email, Url::fromUri('mailto:' . $email))->toRenderable();
mbomb007
  • 3,788
  • 3
  • 39
  • 68
0

Preferably none:

l() is useful for the output of internal links:

it handles aliased paths and adds an 'active' class attribute to links that point to the current page (for theming)" see reference

You need none of the above. Same goes for url(). You CAN use them, but why not keeping it simple and just use the HTML anchor tag directly.

zendka
  • 1,074
  • 12
  • 11
0

In Drupal 9 I found no other solution than:

$this->t('<a href="@link">This is a mail link</a>', ['@link' => 'mailto:mail@example.com']);
tis
  • 5
  • 5