自製郵件發送程式
目的: 以 perl、shell script 自製可夾帶檔案 (使用 MIME 格式) 的郵件發送程式
系統需求: perl、sendmail
vi sendmail.pl
#!/usr/bin/perl -w
use strict;
sub usage() {
print qq(usage: \"$0 [from:user] [to:user] [subject] < mailbody\"\n);
}
my $domain = "your.domain";
my($from,$rcpt,$subject);
if (defined($ARGV[0])) {
if ($ARGV[0] =~ qq(\@)) {
$from = qq($ARGV[0]);
} else {
$from = qq($ARGV[0]\@$domain);
}
} else {
usage();
exit 1;
}
if (defined($ARGV[1])) {
if ($ARGV[1] =~ qq(\@)) {
$rcpt = qq($ARGV[1]);
} else {
$rcpt = qq($ARGV[1]\@$domain);
}
} else {
usage();
exit 1;
}
if (defined($ARGV[2])) {
$subject = qq($ARGV[2]);
} else {
usage();
exit 1;
}
open(SENDMAIL, "| /usr/sbin/sendmail.sendmail -oi -t -f$from")
|| die qq(Cannot open sendmail output: $!\n);
print SENDMAIL <<EOF;
From: $from
To: $rcpt
Subject: $subject
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="thisisatest"
This is a multi-part message in MIME format.
--thisisatest
Content-Type: text/plain; charset=utf-8
Content-Disposition: inline
EOF
while (<STDIN>) {
print SENDMAIL;
}
print SENDMAIL <<EOF;
--thisisatest--
EOF
close (SENDMAIL);
vi attach.sh
#!/bin/sh
filename=$(echo $1 | awk 'BEGIN{FS="/"}{print $NF}')
realfile=$1
echo "
--thisisatest
Content-Type: application/octet-stream; name=\"${filename}\"
Content-Disposition: attachment; filename=\"${filename}\"
Content-Transfer-Encoding: base64
"
base64 $realfile
使用方法
- sendmail.pl 寄件者 收件者 主旨
鍵盤輸入郵件內容
鍵盤輸入郵件內容
鍵盤輸入郵件內容
(Ctrl + D)- sendmail.pl 寄件者 收件者 主旨 < 郵件內容檔案
- (cat 郵件內容檔案; attach.sh 夾檔1; attach.sh /path/to/夾檔2) | sendmail.pl 寄件者 收件者 主旨
ps. 使用前記得先修改 sendmail.pl 裡面的 $domain 變數
實例說明
# adan 與 bob 都是本機帳號
sendmail.pl adan bob "This is a test" < mail.body# 寄給外部帳號
sendmail.pl adan someone@somewhere.com "This is a tes" < mail.body# 偽裝寄件人
sendmail.pl billgates@microsoft.com someone@somwhere.com "This is a test" < mail.body# 夾帶檔案
(cat mail.body; attach.sh file1.txt; attach.sh file2.jpg) | sendmail.pl adan bob "This is a test"# 寄給本機所有使用者 (分別夾帶不同檔案)
vi userlist_generator.sh#!/bin/sh
if [ "$1" == "" ]; then
echo "Usage: $0 outputfile"
exit 1
elif [ -e "$1" ]; then
true > $1
fi
cd /home
for i in *; do
id $i > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo $i >> $1
fi
donesh userlist_generator.sh /tmp/user_list.txt
for i in $(cat /tmp/user_list.txt); do \
(cat mail.body; attach.sh file1.txt; attach.sh userfiles/$i.txt) | sendmail.pl root $i "公告" \
done