分类:
2010-04-02 16:11:32
在监控系统中,监控服务器很多,如果要发送报警邮件,不必在每一台监控服务器上都开启SENDMAIL服务,只需要找一台机器开启SENDMAIL,通过以下脚本,用传统的SMTP的方式在监控机上都能发送报警邮件。
一、SENDMAIL的配置修改
(1)修改/etc/mail/sendmail.cf,将SMTP的端口监听在所有的IP上。
DaemonPortOptions=Port=smtp,Addr=0.0.0.0, Name=MTA
(2)修改/etc/mail/access,中继开放给要发送报警邮件的监控机。
127.0.0.1 RELAY
192.168.0.1 RELAY
192.168.0.2 RELAY
(3)重启SENDMAIL
/etc/init.d/sendmail restart
(4)开启随机自启
chkconfig --level 35 sendmail on
(5)测试邮件发送
mail -s "test mail" liyanling_sh@hotmail.com < /tmp/test.txt
二、发送邮件需要用的模块Mail::Sender
三、中文字符编码问题
注意:要用charset => 'gb2312',否则发送中文会有乱码,我之前用encoding=>’gb2312’,结果邮件正文不是乱码,可标题却变成了空白。
#!/usr/bin/perl
###################################################
# send_mail.pl
# Send mail.
# Created by qiudi(Liyanling): 2010.4.2
# Last modified by qiudi(Liyanling): 2010.4.2
###################################################
use strict;
use warnings;
use Mail::Sender;
use Time::localtime;
my $logtime = sprintf("%d-%02d-%02d %02d:%02d:%02d",
localtime(time())->year+1900,localtime(time())->mon+1,
localtime(time())->mday,localtime(time())->hour,
localtime(time())->min,localtime(time())->sec);
sub send_mail
{
my $message = "以下是perl发送邮件测试。";
my $space = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
if ($message ne "")
{
$message ="您好!\n $message\n\n\n"."
$message .= $space." Monitor center\n";
$message .= $space." Qiudi(Liyanling)\n";
$message .= $space.$logtime;
my $subject = "邮件测试";
my $mailhost = '192.168.0.1';
my $mailfrom = 'qiudi@taobao.com';
my $mailto = 'liyanling_sh@hotmail.com';
my $ccaddr = 'qiudi@taobao.com';
print "Send mail ......\n";
my $sender = new Mail::Sender{
smtp => $mailhost,
from => $mailfrom,
};
If ($sender->MailMsg({
to => $mailto,
cc => $ccaddr,
subject => $subject,
msg => $message,
charset => 'gb2312'
}) < 0) {
die "$Mail::Sender::Error\n";
}
print "Mail send OK.\n";
$sender->Close;
}
}