[Tex/LaTex] Typesetting email address

addressestypography

I have found this answer by Will Robertson on how to typeset an email address:

\documentclass{article}
\usepackage{color,hyperref}

\catcode`\_=11\relax
\newcommand\email[1]{\_email #1\q_nil}
\def\_email#1@#2\q_nil{%
  \href{mailto:#1@#2}{{\emailfont #1\emailampersat #2}}
}
\newcommand\emailfont{\sffamily}
\newcommand\emailampersat{{\color{red}\small@}}
catcode`\_=8\relax    

\begin{document}
\email{foobar@gmail.com}
\end{document}

The problem is that it doesn't work if there is an underscore in the address. How do I add such a feature?

Best Answer

The easiest way is to detokenize the text:

\documentclass{article}
\usepackage{color,hyperref}
    \catcode`\_=11\relax
    \newcommand\email[1]{\_email #1\q_nil}
    \def\_email#1@#2\q_nil{%
      \href{mailto:#1@#2}
        {{\emailfont\detokenize{#1}\emailampersat\detokenize{#2}}}%
    }
    \newcommand\emailfont{\sffamily}
    \newcommand\emailampersat{{\color{red}\small@}}
    \catcode`\_=8\relax   
\usepackage[T1]{fontenc}

\begin{document}
\email{foo_bar@gmail.com}
\end{document}