简体   繁体   中英

Formatting mail body sent from Perl script to include lines and spaces

I need to send an mail through my perl script:

use MIME::Lite;

GetOptions(
    'mail|m:s' =>\$recipients
)
my @recipients = split(/,/, $recipients);

sub sendmail {
    chomp @recipients;
    $to = "@recipients";
    $from = 'xyz@gmail.com';
    $subject = 'Output';

    $msg = MIME::Lite->new(
        From     => $from,
        To       => $to,
        Subject  => $subject,
        Data     => $mailbody
    );

    $msg->attr("content-type" => "text/html");
    $msg->send;
    print "Email Sent Successfully\n";
}

Here, I am appending output to mailbody like:

mailbody.=qq(Welcome\n); 

which are statements containing output which has to be emailed.

How can I format this output to include additional lines and/or spaces? I think \\n or even lots of spaces are also not accepted by mailbody.=qq(Welcome\\n); , which results in a single line of content.

You've said:

 "content-type" => "text/html" 

This means you are writing HTML (or at least telling the email client that you are).

If you want to send plain text and format it using literal whitespace, then don't claim to send HTML!

 "content-type" => "text/plain"

If you want to send HTML, then write HTML which has the formatting you want (eg use <p>...</p> to indicate paragraphs, and style="text-indent: 1em;" to indent the first line of a block).

If you want to send HTML (as your content-type implies) then you need to use HTML tags ( <br> , <p>...</p> , etc) to format your text.

If you want to use newlines to format your text, then you need to change your content-type to text/plain .

A few other suggestions:

  • I wouldn't recommend MIME::Lite. These days, you should use something from the Email::* namespace - perhaps Email::Sender or Email::Stuffer (I think I mentioned this yesterday).
  • You should chomp() $recipients before splitting it into @recipients .
  • You use @recipients inside sendmail() , but you don't pass the array to the subroutine. It's bad practice to use global variables within a subroutine - it renders your subroutine less portable and harder to maintain.
  • MIME::Lite expects multiple recipients in a comma-separated string. So splitting $recipients into @recipients is pointless.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM