You tagged this with 'perl' too, so here's a perl solution. The "BETWEEN" clause is an easy way to only process so much data at a time, since the selectall_arrayref call will (under current versions of DBI modules) load all the data you ask for into memory.
mysql> insert into mail_attachs values ( 1, 'abc' ), ( 2, 'def' );
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
$ cat extract.pl
#!/usr/bin/perl
use strict;
use warnings;
use DBI;
my $output_dir = '/home/jmccarthy/mail_attachs';
my $dbh = DBI->connect_cached("DBI:mysql:database=test;host=dbmachine",
'username', 'password');
die "cannot connect, $DBI::err" if ! $dbh;
my $rows = $dbh->selectall_arrayref("SELECT attachid, filecontent FROM mail_attachs
WHERE attachid BETWEEN ? AND ?",
{ Slice => {} }, # get back better-self-documenting hashrefs, instead of arrayrefs
1, 1000); # values for the ?'s above
die "selectall_arrayref failed, $DBI::err" if $DBI::err;
for my $row (@$rows) {
open my $fh, '>', "$output_dir/file$row->{attachid}"
or die "cannot write $row->{attachid}, $!";
print $fh $row->{filecontent}
or die "cannot print to $row->{attachid}, $!";
close $fh
or die "cannot close $row->{attachid}, $!";
print "wrote $row->{attachid}\n";
}
$ ./extract.pl
wrote 1
wrote 2
$ head mail_attachs/file*
==> mail_attachs/file1 <==
abc
==> mail_attachs/file2 <==
def