Mail merge in LaTeX

On 31 okt 2008, at 03:52, Michael Hanson wrote:

I have an existing Excel worksheet with contact information that I'd like to “mail merge” into a set of LaTeX-generated letters.  Ideally, I'd like to be able to just push a button in TeXShop and have this work – maybe a macro or engine?  I’m willing to learn some basic coding to facilitate a relatively automated solution, but I’m not in a position to use some of the LaTeX mail merge suggestions I have seen on the web – my lisp or mysql or awk skills are non-existent, for example.  I'd also prefer to avoid cutting and pasting the data into another file format (such as plain text) – I might as well paste them into individual LaTeX documents at that point.  Any suggestions based on personal experience with a particular solution would be especially welcome.

Here is the solution I created using PHP (installed by default on Mac OS X).

This is what I wrote almost 4 years ago to Wendy McKay:

It isn’t too hard, but it requires the php language, at least in the solution I found. The php file contains some further – hopefully helpful – comments.


  place both attaached files in the same directory

  php SimpleMailMerge.php > SimpleMailMerge.tex
  pdflatex SimpleMailMerge.tex

The data-base file format is near trivial: the fields are numbered from 0, and separated by and exclamation mark - but it could be changed to whatever you want, make sure you adjust the php source.

In your template the fields can be referenced as $elements[0], $elements[1], etc. I have chosen to use the first field for the address and the second for the “dear …” part. The part that may be confusing at first is that php scripts can contain plain text and program code, and in this approach, you have to change the template inside the php file.

You will need to change the file reading code to CSV, look on for documentation, the syntax is easy enough to be usable.

Note and Disclaimer

This code is placed in the public domain. It is entirely unsupported. Use at your own risk. I’m not even interested in bug reports, questions will go unanswered. Share and enjoy.

Items for downloading. The first file should get an extension of .php, but is send out as .txt to avoid server issues.