23 March 2005
This post may be outdated due to it was written on 2005. The links may be broken. The code may be not working anymore. Leave comments if needed.



这里使用 MIME::Lite 模块来发送附件。分为两种情况,一种是 SMTP 服务器不需要验证的,另一种是需要验证/auth 的。

情况一:SMTP 服务器不需要验证

这种情况下可以参考 perldoc MIME::Lite. 还有个更详细的例子在 Cooking with perl.
一个简单的 Example:

use MIME::Lite;
my $msg = MIME::Lite->new(From    => [email protected]',
             To      => [email protected]',
             Subject => 'My photo for the brochure',
             Type    => 'multipart/mixed');
$msg->attach(Type        => 'image/jpeg',
             Path        => '/Users/gnat/Photoshopped/nat.jpg',
             Filename    => 'gnat-face.jpg');
$msg->attach(Type        => 'TEXT',
             Data        => 'I hope you can use this!');
#$msg->send(  );            # default is to use sendmail(1)
# now we use smtp.
$msg->send('smtp', 'mailserver.example.com');

情况二:SMTP 服务器需要验证/auth

现在的 SMTP 服务器大部分都需要验证,我猜测可能的原因是为了防止垃圾邮件。
MIME::Lite 中是不支持 SMTP 验证/auth 的。所以我们一般将 MIME::Lite 转为 string, 然后通过验证后的 Net::SMTP 来发送。详细的代码如下(已测试成功):

use Net::SMTP;
use MIME::Lite;

# setting
my $mailhost = 'smtp.163.com';
my $username = 'usr';
my $password = 'pwd';
my $from = [email protected]'; # your email on that smtp host
my $to = [email protected]'; # the recipient
my $subject = 'It\'s a test mail with attachment'; # the email title
my $content = 'emailed from fayland.'; # the content of email
my $attachment = 'E:/test.gif';

$smtp = Net::SMTP->new($mailhost, Timeout => 120, Debug => 1);

# anth login
$smtp->auth($username, $password);

# attachment
my $msg = MIME::Lite->new(
    From    => $from,
    To      => $to,
    Subject => $subject,
    Type    => 'TEXT',
    Data    => $content,

# Attach 
    Type     => 'image/gif', # the attachment mime type
    Path     => $attachment, # local address of the attachment
    Filename => 'asuwish.gif', # the name of attachment in email

my $str = $msg->as_string() or die "Convert the message as a string: $!\n";



blog comments powered by Disqus