I am following the example from this website to send an email using Perl. The code looks like so:
my $hostname = `hostname`;
my $this_day = `date`;
my $email = "i.h4d35\@gmail.com";
my $to = "$email";
my $from = "admin\@$hostname";
my $subject = "SCHEDULE COMPLETE - $this_day";
my $message = "Student schedule for today, completed for the following students: \n\n$names\n\nHave a nice day...";
open(MAIL, "|/usr/sbin/sendmail -t");
print MAIL "To: $to\n";
print MAIL "From: $from\n";
print MAIL "Subject: $subject\n\n";
print MAIL $message;
close(MAIL);
The mail gets sent but the subject appears in the body of the mail and the email has no subject. How do I fix this?
PS: Have not gotten around to using MIME::Lite
yet as I am still learning this.
#!/usr/bin/perl use MIME::Lite; $to = '[email protected]'; $cc = '[email protected]'; $from = '[email protected]'; $subject = 'Test Email'; $message = 'This is test email sent by Perl Script'; $msg = MIME::Lite->new( From => $from, To => $to, Cc => $cc, Subject => $subject, Type => 'multipart/mixed' ); # Add your text ...
Just like the SendMail Utility, MIME::Lite Module also allows the users to send HTML formatted mails using the perl-script. $message = '<h1>H1 is the main heading</h1><p><img src="image_source_with_extension" /></p>'; The above code will format your mail by following HTML syntax.
use Net::SMTP::Multipart; $to1 = "sam\@bogus.com"; $to2 = '[email protected]'; $smtp = Net::SMTP::Multipart->new($smtpserver); $smtp->Header(To => [ $to1, $to2, '[email protected]' ], From => "junk\@junk.com", Subj => "This is a test."); $smtp->Text("Hello, world!\
Using examples from websites is a bad idea.
Especially any website that instructs you to craft and send low-level formats directly.
You should not implement any of the following formats manually:
Which lots of websites unhelpfully detail how to do, when they should simply be telling you how to achieve these tasks with a module.
Here is a much more simple approach, using Email::Sender and Email::Simple, both quality pieces of software written by somebody who deals with Email for a living.
use strict;
use warnings;
my $hostname = `hostname`;
my $this_day = `date`;
use Email::Simple;
use Email::Simple::Creator;
use Email::Sender::Simple qw(sendmail);
my $email = Email::Simple->create(
header => [
From => "admin\@$hostname",
To => "i.h4d35\@gmail.com",
Subject => "SCHEDULE COMPLETE - $this_day",
],
body => "Student schedule for today, completed for the following students: \n\n$names\n\nHave a nice day..."
);
sendmail($email);
The output of hostname
includes a newline, so $from
contains a newline, so the Subject:
line appears after a pair of newlines, so it’s interpreted as being in the message body. Easy to fix:
chomp($hostname);
You may find a similar issue with date
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With