perlでSMTP経由でメールを送信する

前準備

yum install perl-Net-SMTP-TLS

mail.pl

#!/usr/bin/perl

use Encode;
use Net::SMTP;
use Net::SMTP::TLS;
use Net::POP3;

$charset="iso-2022-jp";
$mime_charset="MIME-Header-ISO_2022_JP";

$smtp_sv = $ARGV[0];
$smtp_port = $ARGV[1];
$smtp_user = $ARGV[2];
$smtp_pass = $ARGV[3];
$from = $ARGV[4];
$to = $ARGV[5];
$subject = $ARGV[6];
$pop3_sv = $ARGV[7] or null; #Optional
$msg='';
while () {
    $msg .= $_;
}

$msg = Encode::encode($charset, $msg);

$from = Encode::encode($mime_charset, $from);
$to = Encode::encode($mime_charset, $to);

chomp $subject;
$subject = Encode::encode($mime_charset, $subject);

if ($pop3_sv) {
    # POP Before SMTP
    $pop = Net::POP3->new($pop3_sv);
    # POP3
    if($pop->login($smtp_user, $smtp_pass) >= 0) {
        $pop->quit;
    }else{
        die "can't login POP3.n";
    }
}

# Connect SMTP
if ($smtp_port == '587') {
    $smtp = Net::SMTP::TLS->new($smtp_sv,
                           Port => $smtp_port,
                           User => $smtp_user,
                           Password => $smtp_pass
                           );
} else {
    $smtp = Net::SMTP->new($smtp_sv
            ,Port => $smtp_port
    );
}

if(!$smtp){
    die "No Server $smtp_sv:$smtp_port n";
}

$smtp->mail($from);
$smtp->to($to);
$date = &date;
$smtp->data();
$smtp->datasend("Date: $daten");
$smtp->datasend("From: $fromn");
$smtp->datasend("To: $ton");
if ($cc) {
    $smtp->datasend("Cc: $ccn");
}
$smtp->datasend("Subject: $subjectn");
$smtp->datasend("Content-Transfer-Encoding: 7bitn");
$smtp->datasend("Content-Type: text/plain;charset="ISO-2022-JP"nn");
$smtp->datasend("$msgn");
$smtp->dataend();
$smtp->quit;

##
# date string
##
sub date {
    $ENV{'TZ'} = "JST-9";
    ($sec,$min,$hour,$mday,$mon,$year,$wday) = localtime(time);
    @week = ('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
    @month = ('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
    $d = sprintf("%s, %d %s %04d %02d:%02d:%02d +0900 (JST)",
    $week[$wday],$mday,$month[$mon],$year+1900,$hour,$min,$sec);

    return $d;
}