gnu@perl has asked for the wisdom of the Perl Monks concerning the following question:

I need to attach files to email and have been using uuencode. I am attaching these uuencoded files as MIME attachments. This has worked fine up until now. Certain email clients (Goldmine, AOL) have a problem with uuencoded info for some reason.

Anyway, I was wondering if someone could tell me how to base64 encode files before sending them. It would appear the only thing I would need to change is the "Content-Transfer-Encoding: UUENCODE" to "Content-Transfer-Encoding: BASE64" in the email header.

I would like a perl method for doing this in code, no modules. I am aware that there are modules to do this (Mime::Lite), but this code will end up on boxes where I cannot add modules.

Your help is greatly appreciated.

Replies are listed 'Best First'.
(z) Re: base64 encoding
by zigdon (Deacon) on Jan 08, 2003 at 14:49 UTC
    If you can't install the module, just use it's code. Streight out of Mime::Base64:
    sub old_encode_base64 ($;$) { my $res = ""; my $eol = $_[1]; $eol = "\n" unless defined $eol; pos($_[0]) = 0; # ensure start at the beg +inning $res = join '', map( pack('u',$_)=~ /^.(\S*)/, ($_[0]=~/(.{1,45})/ +gs)); $res =~ tr|` -_|AA-Za-z0-9+/|; # `# help emacs # fix padding at the end my $padding = (3 - length($_[0]) % 3) % 3; $res =~ s/.{$padding}$/'=' x $padding/e if $padding; # break encoded string into lines of no more than 76 characters ea +ch if (length $eol) { $res =~ s/(.{1,76})/$1$eol/g; } return $res; }

    -- Dan

      I also am looking for a simple way to base64 a file. I have a small mail module that sends formatted e-mails via sendmail and I want to add the ability of sending attachmnets. The code you posted looks like the answer; question:- is the old_encode_base64 sub expecting a file to be read in line by line or should the whole file be slurped up into one scalar variable and the sub called with that variable?

        I believe you're expected to slurp the whole file you want to encode, and hand it over to the sub. Depending on the filesize, it might hurt your machine though. I'm not sure, but I doubt you can encode a file line by line and get the same result.

        -- zigdon

Re: base64 encoding
by aging acolyte (Pilgrim) on Jan 08, 2003 at 14:51 UTC
    gnu@perl

    Whilst you may not be able to add modules to the perl lib on a box you should be able to put them in some local directory and then access them via

    use lib "/home/usr/gnu/perl/mods/base64encode"; use base64encode;

    A.A.

Re: base64 encoding
by Callum (Chaplain) on Jan 08, 2003 at 14:46 UTC
    Either statically include the module in your code, or examine the code employed in the modules to determine what the critical aspects of the process are. Obviously, taking into account any copyright and/or IP issues.