perl发email:能够用来发附件的gmail代码


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

use Authen::SASL;
use MIME::Lite;
use Net::SMTP::SSL;

send_mail( 'test', 'xxx<br><img src="cid:testimg">', 
    #mime_type => 'text/html', 
    from => 'a@gmail.com', 
     to =>  'c@163.com',

    
    host => 'smtp.gmail.com', 
    usr => 'a@gmail.com', 

    passwd => 'xxxxxx', #
    port => 465, 
    #timeout => 30, 
    #debug => 0, 

    attach => [ 
        {
            mime_type => 'image/png', 
            id => 'testimg', 
            path => 'C:\Users\Administrator\Desktop\1.png', 
        },
    ], 
);

sub send_mail {
    my ($subject, $message, %opt) = @_;

    my $msg = make_mail_msg($subject, $message, %opt);

    my $smtp = Net::SMTP::SSL->new(
        $opt{host},
        Port    => $opt{port} || 465,
        Timeout => $opt{timeout} || 30,
        Debug   => 1,
    ) or die "Net::SMTP::SSL create fail\n";

    if($opt{usr} and $opt{passwd}){
        $smtp->auth( $opt{usr}, $opt{passwd} ) || die "smtp auth fail";
    };

    $smtp->mail( $opt{from} );
    $smtp->to( format_mail_addr($opt{to}) );
    $smtp->cc( format_mail_addr($opt{cc}) ) if($opt{cc});
    $smtp->bcc( format_mail_addr($opt{bcc}) ) if($opt{bcc});

    $smtp->data();
    $smtp->datasend( $msg->as_string );
    $smtp->dataend();

    $smtp->quit;
} ## end sub send_mail

sub make_mail_msg {
    my ($subject, $message, %opt) = @_;

    my $msg = MIME::Lite->new(
        Subject => $subject,
        Type    => 'multipart/alternative', 
    );

    my $body = MIME::Lite->new( 
        Type => $opt{mime_type} || 'text/html', 
        Data => $message, );
    $body->attr( 'content-type.charset' => $opt{charset} || 'UTF-8' );
    $msg->attach($body);

    for my $f (@{$opt{attach}}) {
        $msg->attach(
            Type => $f->{mime_type},
            Id   => $f->{id},
            Path => $f->{path},
        );
    } 

    return $msg;
}

sub format_mail_addr {
    my ($m) = @_;
    return ref($m) eq 'ARRAY' ? @$m : $m;
}

发表回复