# Exercise 11: Mail Merging With Envelope Labels using newlfm.cls, envlab.sty and datatool.sty (Solution)

This is a solution to Exercise 11, which is an improvement over the example document mail-merging-newlfm-labels. You need the sample files people.csv and country-codes.csv. Alternatively, if you want to use data from the samples SQL database, remember to use datatooltk to import the data to a .dbtex file and load it using \DTLloaddbtex as described in Loading Data From a .dbtex File.

\documentclass[stdletter,nocapaddress,avery5164biglabel]{newlfm}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

\usepackage[british]{babel}
\usepackage{datatool}

\newcommand{\ifcsbool}[3]{%
\ifboolexpr
{
test{\ifdefstring{#1}{true}} or
test{\ifdefstring{#1}{1}}
}
{#2}{#3}%
}

\phonefrom{0123456789}

\regarding{A sample letter}

\closeline{Yours sincerely}

\cclist{Prof Important Person\\Dr Bor Ing}

\encllist{Photocopy of something interesting\\
Photocopy of something rather dull}

\psitem{this is a postscript}

% Define a command to store the labelling information for later use:
\newcommand*{\mylabels}{}

\begin{document}

\DTLforeach*{people}% data
{% assignments
\Id=id,%
\Surname=surname,%
\Forenames=forenames,%
\Title=title,%
\Town=town,%
\County=county,%
\Postcode=postcode,%
\CountryCode=country,%
\Subscribed=subscribed%
}
{%
\ifcsbool{\Subscribed}
{%
\xDTLassignfirstmatch{countries}{code}{\CountryCode}{\CountryName=name}

\nameto{\DTLifnullorempty{\Title}{}{\Title\ }\Forenames\ \Surname}
\DTLifnullorempty{\County}{}{\County\\}\Postcode\\\CountryName
}

\greetto{Dear \DTLifnullorempty{\Title}{\Forenames}{\Title} \Surname}

% Append labelling information for this entry to \mylabels

\eappto\mylabels{%
\noexpand\mlabel
University of Somewhere\noexpand\\%
Some City AB3 4YZ}%
{\DTLifnullorempty{\Title}{}{\Title\ }\Forenames\ \Surname\noexpand\\%
\Town\noexpand\\%
\DTLifnullorempty{\County}{}{\County\noexpand\\}%
\Postcode\noexpand\\\CountryName
}%
}

\begin{newlfm}

This is an imaginary letter.

This is the second paragraph of the letter.

\end{newlfm}
}%
{}% not subscribed
}

\startlabels

\mylabels
\end{document}

If you want upper case labels, this is now possible in the construction of \mlabel:
eappto\mylabels{%
\noexpand\mlabel
UNIVERSITY OF SOMEWHERE\noexpand\\%
SOME CITY AB3 4YZ}%
{\DTLifnullorempty{\Title}{}{\noexpand\MakeUppercase{\Title}\ }%
\noexpand\MakeUppercase{\Forenames\ \Surname}\noexpand\\%