Search code examples
htmlperlemailmason

perl : HTML::Mason - Print a perl hash inside HTML tags in a tabular format


I am trying to send a html email (report) about the values in a hash. But I couldnt print the hash values in a table format. I am using HTML::Mason to execute my perl commands (looping through a hash) and printing it in the end of report. But my perl code is not getting executed.

use HTML::Entities;
use Mail::Sendmail;
use MIME::Lite;
use Term::ANSIColor;
use Time::localtime;
use HTML::Mason;

my $ti = localtime;
my ( $day, $month, $year ) = ( $ti->mday, $ti->fullmonth, $ti->year );

# DEFINE A HASH
%coins = ( "Quarter" => 25, "Dime" => 10, "Nickel" => 5 );

$html = <<END_HTML;
   Please direct any questions to <a href="mailto:[email protected]">MyEmailID</a><br><br>

  <table border='1'>
   <th>Keys</th><th>Values</th>
% while (($key, $value) = each(%coins)){       
   <TR>     
   <TD><% $key %></TD>      
   <TD><% $value %></TD>      
   </TR>       
% }
  </table>;

END_HTML

$msg = MIME::Lite->new(
    from    => '[email protected]',
    To      => '[email protected]',
    Subject => 'Report',
    Type    => 'multipart/related'
);
$msg->attach(
    Type => 'text/html',
    Data => qq{
        <body>
        <html>$html</html>
        </body>
    },
);

MIME::Lite->send( 'smtp', 'xxxs.xxxx.xxxxx.com' );
$msg->send;

Solution

  • Since you're only wanting to generate a table, you could do this easily without using HTML::Mason:

    use HTML::Entities;
    use Mail::Sendmail;
    use MIME::Lite;
    use Term::ANSIColor;
    use Time::localtime;
    
    my $ti = localtime;
    my ( $day, $month, $year ) = ( $ti->mday, $ti->fullmonth, $ti->year );
    
    # DEFINE A HASH
    my %coins = ( "Quarter" => 25, "Dime" => 10, "Nickel" => 5 );
    
    my $html = '<table border="1">
    <thead><th>Keys</th><th>Values</th></thead>
    <tbody>';
    
    while ( my($key, $value) = each(%coins)) {
        $html .= "<tr><td>$key</td><td>$value</td></tr>";
    }
    $html .= "</tbody></table>";
    
    my $greeting = 'Please direct any questions to <a href="mailto:[email protected]">MyEmailID</a><br><br>';
    my $outtro = '<br><br>See yas later, alligator!';
    
    $html = $greeting . $html . $outtro;
    
    $msg = MIME::Lite->new(
        from    => '[email protected]',
        To      => '[email protected]',
        Subject => 'Report',
        Type    => 'multipart/related'
    );
    $msg->attach(
        Type => 'text/html',
        Data => qq{
            <body>
            <html>$html</html>
            </body>
        },
    );
    
    MIME::Lite->send( 'smtp', 'xxxs.xxxx.xxxxx.com' );
    $msg->send;
    

    Unless you need a lot of complexity in your email, it is probably not worth using HTML::Mason for this purpose. If you're going to use HTML::Mason for an email, you'll need to set up your script to call it - see the pod for details. You can't just embed Mason commands in a string, unfortunately.