Sunday, September 14, 2008

LWP is Simple.

While I'm on the nerd tip, this is the simplest example I can get to grab the contents of a URL, with a optional username/password and/or proxy:

 
#!/usr/bin/perl

my $proxy = undef;
my $user = undef;
my $pass = undef;
my $url = 'http://localhost';

# Create a user agent object
require LWP::UserAgent;
my $ua = LWP::UserAgent->new;

if($proxy){
$ua->proxy(
['http', 'ftp'],
$proxy
);
}

# Create a request
my $req = HTTP::Request->new(
GET => $url
);
# Pass request to the user agent and get a response back
my $res = $ua->request($req);
if(
defined($user) &&
defined($pass)
){
$res->authorization_basic(
$user,
$pass
);
}
# Check the outcome of the response
if ($res->is_success) {
return $res->content;
}
else {
warn $res->status_line;
return undef;
}
}



Wishing LWP::Simple would do this, but. Nope.

Saturday, September 13, 2008

MIME Trickery with MIME::Parser and friends

You can attach attachments to a multipart/related email message entity (say, a email message created from a website, with the images attached to the message itself) by creating a new multipart/mixed entity, and having the first part be that multipart/related entity and the rest being your new attachments. For example:

 
#!/usr/bin/perl
use strict;

use :MyMIMELiteHTML;
use MIME::Parser;
use MIME::Entity;

my $HTMLurl = 'http://localhost';
my $jpg_path = '/Users/justin/Desktop/4.jpg';


my $mailHTML = new MyMIMELiteHTML(
'IncludeType' => 'cid',
);

my $MIMELiteObj = $mailHTML->parse($HTMLurl) ;


my $msg_as_string = $MIMELiteObj->as_string;


my $parser = new MIME::Parser;

my $entity = $parser->parse_data($msg_as_string);


# Attach stuff to it:


my $cont_entity = MIME::Entity->build(Type => "multipart/mixed");
$cont_entity->add_part($entity);
$cont_entity->attach(
Path => $jpg_path,
Type => "image/jpg",
Encoding => "base64",
Disposition => "attachment",
);

print $cont_entity->stringify;



MyMIMELiteHTML is just my version of MIME::Lite::HTML, with a few bug fixes and changes to fit in my program better.


http://search.cpan.org/~alian/MIME-Lite-HTML-1.22/HTML.pm


I've tried also just added the attachments to the multipart/related entity, but the new attachments never can be found - at least in Mail.app (Gmail? Yes?), unless you put in a bogus Content-ID header for the attachement - which actually could come in handy in some rare cases, but I digress...