perl模块之MIME::Lite发送有附件的邮件

#!/usr/bin/perl
use strict;
use warnings;

use MIME::Lite; #这个用来组织邮件信息内容
use Pod::Usage;
use Getopt::Long;
use MIME::Base64;
use MIME::Words qw/:all/;
use Authen::SASL;
my $options = {
        from    => 'bot',
};

GetOptions( $options,
            'help|?',       # 帮助
            'html!',        # HTML 邮件支持
            'subject=s',    # 邮件标题
            'from=s',       # 发件人
            'to=s',         # 收件人
            'cc=s',         # 抄送
            , # 附件
        ) or pod2usage();

pod2usage() if $options->{help};
pod2usage() unless $options->{subject} and $options->{to};

my $cc   = $options->{cc} || '';
my $lines = <>;

#$lines=encode_base64("$lines",'');

# 邮件服务器的连接信息
MIME::Lite->send("smtp", "smtp.163.com",AuthUser=>‘myusername',AuthPass=>'******',Debug => 0, Timeout => 60);

# 组织邮件信息内容
my $msg = MIME::Lite->new(
                From => $options->{from},
                To => $options->{to},
                cc => $cc,
                Subject => encode_mimeword($options->{subject},'b','utf-8'),
                #Subject => $options->{subject},
                #Subject => '=?utf-8?B?'.encode_base64("$options->{subject}").'?=',
                Type => 'multipart/mixed'
                );


if (not $options->{html} ){
    $msg->attach(   
            Encoding =>'base64',
            Type =>'text/plain;charset=utf-8',
            Data => $lines
            );
    
}else{
    $msg->attach(
            Encoding =>'Base64',
            Type =>'text/html; charset=utf-8',
            Data => $lines
            );
}
### attach: $options->{attach}
for ( 0 .. $#{$options->{attach}} ) {
    $msg->attach(
           Type =>'auto', #建议设置成auto要不就application/octet-stream
           Path => $options->{attach}[$_], 
           Encoding => 'Base64',
           Disposition => 'attachment'
           );
}
print STDERR "正在发送.......\n"; 
$msg->send() or die "Couldn't send whole message: $!\n";

__END__

=head1 NAME

sendMail - 发送邮件

=head1 SYNOPSIS

sendMail [选项] [正文文件名]

正文文件名省略时,邮件正文来自标准输入

选项:

    --help                  显示帮助信息
    --subject               邮件标题
    --from                  发件人
    --to                    收件人
    --cc                    抄送
    --html                  发送 HTML 格式邮件
    --attach                发送附件

调用方法:

echo "aaaaa你好---"|perl demo.pl --subject hello --from --to --attach /home/a.zip


(责任编辑:admin)

你可能感兴趣的:(perl模块之MIME::Lite发送有附件的邮件)