2021-05-12 14:32:11
Linux Shell發郵件筆記
2020-06-16 17:38:32
Linux作為首屈一指的伺服器級別的作業系統,郵件系統的使用非常簡單(一行命令),雖然網上已經有很多Shell發郵件的文章貼文足夠參考使用,例如這一篇寫的比較翔實[附1],本文基本上也是按其過程操作,這裡自己再寫一遍是為了以自己的方式總結和學習。
①安裝所需軟體包
yum install -y sendmail
yum install -y sharutils
wget ftp://ftp.gnu.org/gnu/mailutils/mailutils-2.2.tar.gz
tar -xzf mailutils-2.2.tar.gz
cd mailutils-2.2 ; ls
./configure
make && make install
DEB式系統(Debian、Ubuntu):
apt-get install sendmail
apt-get install mailutils
apt-get install sharutils
②簡單說明
DEB系統的apt提供了完整的源,可以直接簡單安裝;RPM系統中“mailutils”包需要手動下載原始碼編譯安裝。“sendmail”提供本地郵件設定和服務管理,“mailutils”提供各種格式和通訊協定的郵件支援,“sharutils”提供附件傳輸。
Ubuntu安裝完成後郵件服務(“sendmail”)預設已經啟動了,CentOS則可能需要手動啟動服務。可以通過檢視進程列表確認是否需要手動啟動服務。
ps aux | grep sendmail
service sendmail start
“sendmail”預設設定是支援本地郵件服務,要開啟外網通訊,需要修改一下組態檔“/etc/mail/sendmail.mc”,找到“127.0.0.1”,修改為“0.0.0.0”。
③發件範例
普通郵件
echo 郵件正文 | mail -s 郵件主題 -t 收件人
例:echo -e "我是一棵蔥n你是一顆蒜" | mail -s Hello -t …………@…….com
郵件內容來自檔案
mail -s subject -t …………@…….com < file
例:mail -s Hello -t …………@…….com < 蔥與蒜.txt
附件郵件
uuencode 原檔名 檔案附件名 | mail -s subject -t …………@…….com
例:uuencode 蔥與蒜.txt 蔥與蒜.txt | mail -s subject -t …………@…….com
一個完整例子:
(echo -e "我是一棵蔥n" ; echo "你是一顆蒜" ; uuencode 蔥.txt 蔥.txt ; uuencode 蒜.txt 蒜.txt) |
mail -s "Hello Gay" -t …………@163.com, …………@qq.com
作為指令碼語言,Python也可以非常方便的進行發郵件[附2]。
附1:shell發郵件命令之mail
目前最常用的就是mail命令了。
(sudo apt-get install mailutils)
也可手動下載安裝:http://mailutils.org/download.html
簡單一行命令實現傳送郵件
echo 'content test' | mail -s "title test" -t abc@hello.com,efg@hello.com,123@world.com-a From:aaa@qq.com
內容由檔案匯入
mail -s "sh mail test" < file1.txt
帶上附件
(uuencode file1.txt file1.txt; uuencode file2.txt file2.txt) | mail -s "title test" -t hello@aaa.com
內容 + 附件
(echo '1111111'; uuencode file1.txt file1.txt; uuencode file2.txt file2.txt) | mail -s "title test" -t hello@aaa.com
多個內容 +多個 附件
(echo '1111111'; echo '22222222'; uuencode file1.txt file1.txt; uuencode file2.txt file2.txt) | mail -s "title test" -t hello@aaa.com
Cent OS 系統上:
下載安裝mailutils
wget ftp://ftp.gnu.org/gnu/mailutils/mailutils-2.2.tar.gz
解壓進入
./configure
make && make install
yum install -y sendmail
yum install sharutils # 使用帶附件功能
service sendmail start
檢視sendmail啟動沒: ps aux |grep sendmail
測試:echo 'content test' | mail -s "title test" -t aaa@b.com
此時發覺只能給公司內部發郵件, 如果需要還能給外面的郵箱(比如我的qq郵箱)發郵件則還需要
vi /etc/mail/sendmail.mc
找到包含Addr的這一行:
DAEMON_OPTIONS(`Family=inet, Name=MTA-v4, Port=smtp, Addr=127.0.0.1')dnl
修改Addr=0.0.0.0 ,表明可以連線到任何伺服器
/etc/mail/sendmail.mc
divert(-1)dnl
#-----------------------------------------------------------------------------
# $Sendmail: debproto.mc,v 8.14.4 2014-02-11 13:02:08 cowboy Exp $
#
# Copyright (c) 1998-2010 Richard Nelson. All Rights Reserved.
#
# cf/debian/sendmail.mc. Generated from sendmail.mc.in by configure.
#
# sendmail.mc prototype config file for building Sendmail 8.14.4
#
# Note: the .in file supports 8.7.6 - 9.0.0, but the generated
# file is customized to the version noted above.
#
# This file is used to configure Sendmail for use with Debian systems.
#
# If you modify this file, you will have to regenerate /etc/mail/sendmail.cf
# by running this file through the m4 preprocessor via one of the following:
# * make (or make -C /etc/mail)
# * sendmailconfig
# * m4 /etc/mail/sendmail.mc > /etc/mail/sendmail.cf
# The first two options are preferred as they will also update other files
# that depend upon the contents of this file.
#
# The best documentation for this .mc file is:
# /usr/share/doc/sendmail-doc/cf.README.gz
#
#-----------------------------------------------------------------------------
divert(0)dnl
#
# Copyright (c) 1998-2005 Richard Nelson. All Rights Reserved.
#
# This file is used to configure Sendmail for use with Debian systems.
#
define(`_USE_ETC_MAIL_')dnl
include(`/usr/share/sendmail/cf/m4/cf.m4')dnl
VERSIONID(`$Id: sendmail.mc, v 8.14.4-4.1ubuntu1 2014-02-11 13:02:08 cowboy Exp $')
OSTYPE(`debian')dnl
DOMAIN(`debian-mta')dnl
dnl # Items controlled by /etc/mail/sendmail.conf - DO NOT TOUCH HERE
undefine(`confHOST_STATUS_DIRECTORY')dnl#DAEMON_HOSTSTATS=
dnl # Items controlled by /etc/mail/sendmail.conf - DO NOT TOUCH HERE
dnl #
dnl # General defines
dnl #
dnl # SAFE_FILE_ENV: [undefined] If set, sendmail will do a chroot()
dnl # into this directory before writing files.
dnl # If *all* your user accounts are under /home then use that
dnl # instead - it will prevent any writes outside of /home !
dnl # define(`confSAFE_FILE_ENV', `')dnl
dnl #
dnl # Daemon options - restrict to servicing LOCALHOST ONLY !!!
dnl # Remove `, Addr=' clauses to receive from any interface
dnl # If you want to support IPv6, switch the commented/uncommentd lines
dnl #
FEATURE(`no_default_msa')dnl
dnl DAEMON_OPTIONS(`Family=inet6, Name=MTA-v6, Port=smtp, Addr=::1')dnl
DAEMON_OPTIONS(`Family=inet, Name=MTA-v4, Port=smtp, Addr=0.0.0.0')dnl
dnl DAEMON_OPTIONS(`Family=inet6, Name=MSP-v6, Port=submission, M=Ea, Addr=::1')dnl
DAEMON_OPTIONS(`Family=inet, Name=MSP-v4, Port=submission, M=Ea, Addr=127.0.0.1')dnl
dnl #
dnl # Be somewhat anal in what we allow
define(`confPRIVACY_FLAGS',dnl
`needmailhelo,needexpnhelo,needvrfyhelo,restrictqrun,restrictexpand,nobodyreturn,authwarnings')dnl
dnl #
dnl # Define connection throttling and window length
define(`confCONNECTION_RATE_THROTTLE', `15')dnl
define(`confCONNECTION_RATE_WINDOW_SIZE',`10m')dnl
dnl #
dnl # Features
dnl #
dnl # use /etc/mail/local-host-names
FEATURE(`use_cw_file')dnl
dnl #
dnl # The access db is the basis for most of sendmail's checking
FEATURE(`access_db', , `skip')dnl
dnl #
dnl # The greet_pause feature stops some automail bots - but check the
dnl # provided access db for details on excluding localhosts...
FEATURE(`greet_pause', `1000')dnl 1 seconds
dnl #
dnl # Delay_checks allows sender<->recipient checking
FEATURE(`delay_checks', `friend', `n')dnl
dnl #
dnl # If we get too many bad recipients, slow things down...
define(`confBAD_RCPT_THROTTLE',`3')dnl
dnl #
dnl # Stop connections that overflow our concurrent and time connection rates
FEATURE(`conncontrol', `nodelay', `terminate')dnl
FEATURE(`ratecontrol', `nodelay', `terminate')dnl
dnl #
dnl # If you're on a dialup link, you should enable this - so sendmail
dnl # will not bring up the link (it will queue mail for later)
dnl define(`confCON_EXPENSIVE',`True')dnl
dnl #
dnl # Dialup/LAN connection overrides
dnl #
include(`/etc/mail/m4/dialup.m4')dnl
include(`/etc/mail/m4/provider.m4')dnl
dnl #
dnl # Default Mailer setup
MAILER_DEFINITIONS
MAILER(`local')dnl
MAILER(`smtp')dnl
附2:【Python】一鍵式發郵件小指令碼
工作中涉及到給客戶定時發郵件,這裡提供一個Python小指令碼,單獨放進一個py小檔案,每次用時import一下非??簡單方便。
# !/usr/bin/python
# -*- coding: utf-8 -*-
#
#
# create_author: 蛙鱖雞鸛狸猿
# create_time : 2016-10-10
# NOTICE : *_*mail config*_*
#
#
import logging
import smtplib
from email import encoders
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
#
#
# class obj
class Mail():
def __init__(self, msg_from, msg_to, msg_subject, text, path_file, host, port, user, password):
self.msg_from = msg_from # 發件箱——————""
self.msg_to = msg_to # 收件箱——————["",""]
self.msg_subject = msg_subject # 郵件主題————""
self.text = text # 郵件正文————""
self.path_file = path_file # 郵件附件————[{"path" : "", "name" : ""}, {"path" : "", "name" : ""}]
self.host = host # 伺服器——————"smtp.163.com"
self.port = port # 埠號——————25
self.user = user # 發件箱使用者———""
self.password = password # 發件箱密碼————""
#
def __str__(self):
tranceback = "An e-mail from "%s" to "%s" under subject of "%s"…………" % (self.msg_from, self.msg_to, self.msg_subject)
return tranceback
#
def csmail(self):
msg = MIMEMultipart()
try:
msg['from'] = self.msg_from
msg['to'] = ','.join(self.msg_to) # because of a BUG of smtplib
msg['subject'] = self.msg_subject
msg.attach(MIMEText(self.text))
for i in self.path_file:
msg_attach = MIMEText(open(i['path'], "rb").read(), "base64", "utf-8")
attach_name = i['name']
msg_attach.add_header("Content-Disposition", "attachment", filename=attach_name)
msg_attach["Content-Type"] = "application/octet-stream"
msg.attach(msg_attach)
except Exception , e:
logging.error("create email under subject "%s" failed! Detail: %s" % (self.msg_subject , e))
exit()
ser = smtplib.SMTP()
try:
ser.connect(host=self.host, port=self.port)
ser.login(user=self.user, password=self.password)
ser.sendmail(msg['from'], self.msg_to, msg.as_string())
ser.quit()
except Exception, e:
logging.error("send email under subject "%s" failed! Detail: %s" % (self.msg_subject , e))
exit()
以下是一個小範例。
MSG = {"msg_from" : "……@163.com",
"msg_to" : ["……@qq.com", "……@…….com"],
"msg_subject" : "Hello收件人",
"text" : "測試郵件(generate by Python2.7.12)",
"path_file" : [{"path" : moudle_base.rount() + "附件1" + moudle_base.curtime() + ".xlsx",
"name" : "附件1" + moudle_base.curtime() + ".xlsx"},
{"path" : moudle_base.rount() + "附件2" + moudle_base.curtime() + ".xlsx",
"name" : "附件2" + moudle_base.curtime() + ".xlsx"}],
"host" : "smtp.163.com",
"port" : 25,
"user" : "……",
"password" : "……"
}
mail = Mail(msg_from=MSG["msg_from"], msg_to=MSG["msg_to"], msg_subject=MSG["msg_subject"], text=MSG["text"], path_file=MSG["path_file"],
host=MSG["host"], port=MSG["port"], user=MSG["user"], password=MSG["password"])
print(mail)
mail.csmail()
也就是把所有的引數放進一個大字典,直接取用就可以了,非常一目了然。
相關文章