Thursday, June 21, 2012

A Simple Perl-Based RSS to Email Program


While many sites offer RSS feeds as a means of keeping up to date with new content, not everyone is as familiar with RSS and RSS feed readers as they are with Email and Email clients.  To deal with this issue, here is a small Perl code snippet which will download an RSS feed, parse out the title and the description associated with each RSS entry, and email out the extracted information.  In the interest of simplicity for the sample code, it extracts the item titles and description from every element in the feed, but with a little modification it could be adapted to only utilize the most recent feed entries.  Running the script periodically to check for new RSS entries could be easily handled via cron jobs or other job scheduler. 

The Email sending portion of the code was tested using Gmail.  

 #!usr/bin/perl

use Email::Sender::Simple qw(sendmail);
use Email::Sender::Transport::SMTP::TLS;
use Email::Simple;
use Email::Simple::Creator;
use XML::RSS::Parser;
use LWP;
use strict;
use warnings;

my $feedurl='http://feeds.feedburner.com/SansInstituteNewsbites?format=xml';

my $ua=LWP::UserAgent->new;
my $response=$ua->get($feedurl);
my $rss=$response->content;

my $parser= new XML::RSS::Parser;
my $feed=$parser->parse_string($rss);
my $feed_title = $feed->query('/channel/title');
my $message =  $feed_title->text_content;
my $count = $feed->item_count;
$message.=" ($count)\n";
foreach my $i ( $feed->query('//item') ) {
  my $node = $i->query('title');
  $message.= '  '.$node->text_content . "\n";
  $node = $i->query('description');
  $message.='  '.$node->text_content;
  $message.= "\n\n";
}
#strips out feed specific html tags because I chose to send plain text email
$message=~s/((<p>)|(<\/p>))//gio;

my $transport = Email::Sender::Transport::SMTP::TLS->new(
   host => 'smtp.gmail.com',
   port => 587,
   username => 'somebody@gmail.com',
   password => 'password'
);

my $email = Email::Simple->create(
    header => [
      To      => '"Somebody" <somebody@gmail.com>',
      From    => '"Somebody Else" <s_else@gmail.com>',
      Subject => "The Latest Updates",
    ],
    body => "$message",
);
sendmail($email, {transport => $transport});

1 comment:

strategi promosi online said...

could you please show how to attach it into website?