As the title says, how can I export only the layer mask? I want to do this because I need to use it in another program.
The easiest way is to click on the Layer Mask thumbnail, on the Layers Dialog, so that it is the active drawable, then copy and paste it to a new image (
ctrl + c,
ctrl + shift + v) , and just export this new image as usual.
(the pasted image will be grayscale, as expected)
Maybe it is the only way using the program's GUI - (there may be variants, but in the end you will have to copy the mask and paste it somewhere else).
It can be done programatically using either the Python or Script-fu console as well - but I think the select/copy/paste as new/export/close cycle is easy enough.
To do it in Python, for example, open the Python console in
then, at the
>>> prompt type:
>>> image = gimp.image_list()
to get a reference to the latest open image (rightmost tab). Increase the the  index to get images more to the left.
Then click on the "browse" button at the bottom, type "png" on the search box, select the "file-png-save" procedure and click on "apply".
It will paste this on your Python prompt:
>>> pdb.file_png_save(image, drawable, filename, raw_filename, interlace, compression, bkgd, gama, offs, phys, time)
without pressing enter, go back with the cursor and edit the line contents so that it read like this instead:
>>> pdb.file_png_save(image, image.layers.mask, "myfile.png", "myfile.png", False, 9, True, True, True, True, True)
<enter> (you will probably want to copy this line to paste it when repeating the command) . This saves the mask of the topmost layer - again, increase the
 index to get the mask of layers lower on the stack.
This may seen too complicated, until you realise that if you want to save all masks of a 20 or so layer image, you do this instead:
>>> for layer in image: ... pdb.file_png_save(image, layer.mask, layer.name + ".png", layer.name + ".png", False, 9, True, True, True, True, True)
And you are done - 20 masks saved.