From 4ac055111effc3c6e068f5df61e82fca903b1e4a Mon Sep 17 00:00:00 2001 From: Max Maischein Date: Sat, 13 Jul 2013 17:15:48 +0200 Subject: Add `inline_images` setting to optionally inline images in the MIME object This is higly convenient if you want to read RSS content offline. --- lib/Feed/HelperRole/Mail.pm | 46 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/lib/Feed/HelperRole/Mail.pm b/lib/Feed/HelperRole/Mail.pm index e0e239e..1279ac8 100644 --- a/lib/Feed/HelperRole/Mail.pm +++ b/lib/Feed/HelperRole/Mail.pm @@ -13,6 +13,10 @@ use Template::Stash::ForceUTF8; use Moose::Util::TypeConstraints; use Try::Tiny; +use List::MoreUtils qw(uniq); +use Text::CleanFragment; +use URI; + subtype 'ArrayOfStr', as 'ArrayRef[Str]'; coerce 'ArrayOfStr', from 'Str', via { [ $_ ] }; @@ -45,6 +49,11 @@ has date_formatter => ( lazy_build => 1, ); +has inline_images => ( + is => 'ro', + isa => 'Bool', +); + sub _build_tt { my ($self) = @_; @@ -91,12 +100,49 @@ sub entry_to_mime { Subject => encode('MIME-Header',$subject), Type => 'multipart/related', ); + + my @images; + if( $self->inline_images ) { + # We expect fairly clean HTML here... + my $base= $entry->link; + my @links= uniq $body=~ m/]*\bsrc="([^"]+)".*?>/ig; + + # Fetch all images, append them + my $ua= $self->user_agent; + for my $image ( @links ) { + my $url= URI->new_abs( $image, $base ); + $self->log->trace( "Retrieving '$url' for inlining" ); + my $res= $ua->get( $url, Referer => $base ); + if( not $res->is_success ) { + $self->log->error("Error retrieving linked image URL '$url': " . $res->status_line ); + next + }; + + my $name= clean_fragment( $image ); + my $id= sprintf "cid:$name"; + + $body=~ s!src\s*=\s*"\Q$image\E"!src="$id"!g; + push @images, { + Type => $res->content_type, + Id => $name, + Data => $res->content, + Filename => $name, + }; + }; + }; + $msg->attach( Type => 'text/html; charset=utf-8', Data => encode('utf-8',$body), Encoding => 'quoted-printable', ); + for my $image (@images) { + # rewrite the HTML to reference the images + $self->log->trace( "Attaching " . $image->{Type} ); + $msg->attach(%$image); + }; + $msg->add('Message-Id', "<$id.feeder\@localhost>"); my @tags = $entry->tags; try { @tags = map { decode('utf-8',$_) } @tags }; -- cgit v1.2.3