用gmail邮箱发邮件,带ssl验证

邮件html正文可嵌入附件图片,例如附件图片id为testimg,邮件正文中引用图片的src地址为cid:testimg

#!/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 => 'someusr@gmail.com', 
    to =>  'someusr@qq.com',
    cc => [ 'someusr@foxmail.com', 'someusr@live.com' ],  
    #bcc => [ 'someusr@yahoo.com', 'someusr@gmail.com' ],  
    
    host => 'smtp.gmail.com', 
    usr => 'someusr@gmail.com', 
    passwd => 'somepasswd', 
    #port => 465, 
    #timeout => 30, 
    #debug => 0, 

    attach => [ 
        {
            mime_type => 'image/png', 
            id => 'testimg', 
            path => 'test.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;
}


Published

13 January 2014

Tags


Share On