Search code examples
htmlperlmime

how to send HTML/Plain Text mail in perl


I am new to the perl language , i want to send the content of plain text file and html text in same email. Where i am getting the file content of a text file but my HTML text is not working i.e i am not a bold sentence in my email . can someone explain how can my html tag to work. Below is my full code. P.S: when i remove the line print MAIL "MIME-Version: 1.0" my html tag works but text file is not working (does not prints line by line).

use MIME::Lite;
my $HOME        ='/apps/stephen/data';
my $FILE        ="$HOME/LOG.txt";
my @HTML        =();


 push(@HTML,"<b>To send the content of a file in email</b><br>\12");
 push(@HTML,`cat $FILE`);

&sendMail;


sub sendMail
{
$sub="TEST";
$from='ABC@ABC.com';
$to='ABC@ABC.com';
open(MAIL, "|/usr/lib/sendmail -t");
        print MAIL "From: $from \12"; print MAIL "To: $to \12";print    MAIL "Cc: $Cc \12";
        print MAIL "Subject: $sub \12";
        print MAIL "MIME-Version: 1.0" ;
        print MAIL "Content-Type: text/html \12";
        print MAIL "Content-Disposition:inline \12";
        print MAIL @HTML;
    close(MAIL);
}

Solution

  • You are preparing to use MIME::Lite but then you forget it all and try to piece together a MIME structure by hand. That's painful and error-prone even if you know exactly what you are doing; you should definitely use a suitable set of library functions instead, to keep your code simple and readable, and focus on the actual task.

    The MIME::Lite documentation shows exactly how to do this, right in the second example in the introduction.

    Adapted to your stub code,

    use MIME::Lite;
    
    use strict;   # always
    use warnings; # always
    
    ### Create a new multipart message:
    $msg = MIME::Lite->new(
        From    => 'ABC@ABC.com',
        To      => 'ABC@ABC.com',
        #Cc      => 'some@other.com, some@more.com',
        Subject => 'TEST your blood pressure with some CAPS LOCK torture',
        Type    => 'multipart/mixed'
    );
    
    ### Add parts (each "attach" has same arguments as "new"):
    $msg->attach(
        Type     => 'text/html',
        Data     => join ('\n', '<b>To see the content of a file in email</b><br/>',
                 '<strong><blink><a href="cid:LOG.txt">click here</a></blink></strong>')
    );
    $msg->attach(
        Type     => 'text/plain',
        Path     => '/apps/stephen/data/LOG.txt',
        Filename => 'LOG.txt',
        Disposition => 'attachment'
    );
    $msg->send();