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:


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;

['http', 'ftp'],

# 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);
defined($user) &&
# 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:

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");
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.

I've tried also just added the attachments to the multipart/related entity, but the new attachments never can be found - at least in (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...