Linux下发送邮件

来源:互联网 发布:python remove delete 编辑:程序博客网 时间:2024/05/16 18:01

我的OS是RHEL5.6-x86-64

1、首先要介绍的是使用mail命令发送邮件,这也许是很多人首先会想到的命令了。

使用mail命令发送邮件需要依赖于sendmail服务,改服务必须启动才能使用mail命令发送邮件,使用-v选项可以开到,当sendmail服务为启动时会有如下错误:

[root@instsvr1 ~]# service sendmail stop
Shutting down sm-client: [  OK  ]
Shutting down sendmail: [  OK  ]
[root@instsvr1 ~]# echo "Test Mail"|mail -v -s "Test Mail" ********@163.com
********@163.com... Connecting to [127.0.0.1] via relay...
********@163.com... Deferred: Connection refused by [127.0.0.1]

mail命令的安装包是:mailx-8.1.1-44.2.2.x86_64.rpm

sendmail的安装包是:sendmail-8.13.8-8.el5.x86_64.rpm

安装介质可以从光盘里面获取或者使用yum安装,在此不赘述,不过这两个东西一般安装系统是可能都会是已安装的!

废话不多说了,直接介绍mail命令的常用格式,其他情况请google或者看man mail或者mail -help

a)简单的发送不带附件的text格式的邮件:

mail -v -s "test mail" user1@163.com user2@163.com -b user3@163.com -c user4@163.com < attached.txt

cat attached.txt | mail -v -s "test mail" user1@163.com user2@163.com -b user3@163.com -c user4@163.com

等价

注:

1)第一个命令使用的重定向符“<”的方式,第二个命令使用的是管道符"|"的方式,这两种方式适合需要发送的内容较多的场景。

2)-v 选项:列印出讯息,例如送信的地点、状态等等。 (verbose)

3)-s选项:邮件标题

3)-b选项:密送用户列表

4)-c选项:抄送用户列表

5)user1@163.com和user2@163.com:就是需要直接发送的用户列表

6)mail命令的其他选项:

      -i选项:忽略TTY的中断信号。这个对于使用嘈杂的电话线路特别有用。

      -I选项:强制mail运行在交互模式,即使不是在终端上输入。当发送邮件时,特殊的字符'~'只在交互模式下起作用。

     -n选项:启动的时候不读取 /etc/mail.rc 脚本文件。

     -N选项:当读取邮件或者编辑邮件的时候不显示邮件头。

     -f选项:用于重mbox或者指定的文件名中读取邮件,仅限于本地使用,并且该选项只能和【iInNv】选项同时使用

     -u选项:用于读取指定本地用户的邮件,并且该选项也只能和【iInNv】选项同时使用

[root@instsvr1 ~]# mail -help
mail: invalid option -- h
Usage: mail [-iInv] [-s subject] [-c cc-addr] [-b bcc-addr] to-addr ...
            [-- sendmail-options ...]
       mail [-iInNv] -f [name]
       mail [-iInNv] [-u user]

如果需要进行交互的输入则可直接使用如下命令:

[root@instsvr1 ~]# mail user1@163.com
Subject: test input
haha
is a test mail
byebyte

Cc:

注释:如果mail命令中不使用-s选项,那么第一个要求输入的就是邮件标题,之后的就是邮件内容了,需要结束编辑的话就使用【Ctrl+D】然后【Enter】回车即可完成。

b)发送带有附件的邮件

使用mail命令发送带附件的邮件时需要使用到uuencode命令,这就需要安装一个叫sharutils的rpm包了,也可以在安装光盘里面找到sharutils-4.6.1-2.x86_64.rpm,也还可以使用yum进行安装:yum install sharutils

首先简要说一下uuencode/uudecode编解码:
uuencode把二进制文件转化成为可读ASCII文件,适合email传输。编码后的文件比原文件要大35%左右,内容第一行一般是"begin, 644, 文件名",最后一行是"end",中间的内容都以"M"开头,满61字符换行。
【注意】如果使用-m参数,则使用base64编码格式

[root@instsvr1 Desktop]# uuencode image.jpg images.jpg
begin 644 images.jpg
M_]C_X``02D9)1@`!`0$`8`!@``#_VP!#``@&!@<&!0@'!P<)"0@*#!0-#`L+
M#!D2$P\4'1H?'AT:'!P@)"XG("(L(QP<*#<I+#`Q-#0T'R<Y/3@R/"XS-#+_
MVP!#`0D)"0P+#!@-#1@R(1PA,C(R,C(R,C(R,C(R,C(R,C(R,C(R,C(R,C(R
M,C(R,C(R,C(R,C(R,C(R,C(R,C(R,C+_P``1"`0`!0`#`2(``A$!`Q$!_\0`
M'P```04!`0$!`0$```````````$"`P0%!@<("0H+_\0`M1```@$#`P($`P4%

省略。。。。。。。。。。。。。。。

M"C#`+R1\N<!FVFMI,\?]M6=OIAOK$74B6\\@N59RC.OW2$7:>/?^></[=;?\
M]4_.FF^MO^>B?G3]BK23>X>UJ7BU&UOZ^19U"^GU+4)[VY.99G+MR<#V&>P'
B`]A5-AFE-Y;G_EHGYTS[7!_ST3_OH5NDDK(RM-N[6I__V0``
`
end

上面命令行参数第一个image.jpg是需要编码的文件名,第二个images.jpg是编码后的文件名(解码时使用),
[root@instsvr1 Desktop]# uuencode image.jpg images.jpg > images.uue
[root@instsvr1 Desktop]# l
total 296
-rw-r--r-- 1 root root 122479 Apr  7 17:24 image.jpg
-rw-r--r-- 1 root root 168779 Apr  7 17:27 images.uue
[root@instsvr1 Desktop]# uudecode images.uue
[root@instsvr1 Desktop]# l
total 420
-rw-r--r-- 1 root root 122479 Apr  7 17:24 image.jpg
-rw-r--r-- 1 root root 168779 Apr  7 17:27 images.uue
-rw-r--r-- 1 root root 122479 Apr  7 17:27 images.jpg

下面举例说说用mail命令结合uuencode快速发送email附件,images.jpg将作为附件名称:

[root@instsvr1 ~]# uuencode image.jpg images.jpg|mail -v -s "images" user1@163.com

在Winows下用Outlook,Foxmail等客户端能自动识别经过uuencode编码的附件。如果附件被收取到Linux/Unix等系统下,如果Linux下的MUA或者客户端不识别,可以手工处理邮件提取相应的部分,用uudecode解码即可。

【注意】这里不能使用-m参数进行base64编码,否则客户端软件无法识别附件。

【注意】其实这种方式并不是很好,因为发送的邮件中出了uuencode编码的附件外,邮件内容是uuencode编码的内容,如果附件较大的话邮件内容就会比较长。并且uuencode编码的附件还需要转码才能看得到,反正我在foxmail里面不能自动解码,很不方便。但是我们可以先打包后再作为附件发送,因为解压工具会可以自动帮忙解码,如:

tar cvf attached.tar attached.txt image.jpg install.log;uuencode attached.tar attached.tar |mail -v -s testmail user1@163.com

可以直接打开attached.tar附件,不需要手工解码,不过这样还是存在邮件内容为附件的uuencode编码内容的情况,所以我们再来介绍另一个发送邮件的工具mutt。

【注意】使用uuencode结合mail发送邮件时不能写邮件内容,因为邮件内容都是附件的uuencode编码


2、接下来介绍的就是强悍的mutt工具了,mutt命令的详细帮助同样请google或者man mutt了或者mutt -help

【注意】由于mutt的功能比较庞大,我在此就不介绍那么详细,只介绍常用的,推荐网文【Mutt中文手册】

mutt工具需要安装mutt-1.4.2.2-3.0.2.el5.x86_64.rpm包,同样还是在安装光盘里面可以找到,或者还是yum install mutt了,安装不赘述。

同样的简单的text格式邮件发送命令与mail命令同,不在赘述,如:

cat attached.txt|mutt -s testmailing user1@163.com

mutt -s testmailing user1@163.com < attached.txt

【注意】使用定向符"<"发送时没有使用管道符"|"快,并且这两种方式当attached.txt中存在中文此类字符时会出现乱码,这时需要设置系统LANG环境变量为utf8,注意是utf8设置成zh_CN.utf8都不行!

export LANG=utf8;mutt -s zhss mrluoe@163.com < attached.txt

还可以使用-e选项指定字符集编码,如:

cat attached.txt|mutt -s html -e "set charset=gb2312" mrluoe@163.com

下面接着介绍使用mutt发送带有附件的邮件了,这就比较简单了,只需使用一个-a选项即可,当需要发送多个附件时使用多个-a选项即可,如:

mutt -s attached -a attached.txt -a image.jpg user1@163.com < attached.txt

使用mutt发送附件就简单了,而且邮件内容同样可以是重定向符"<"或者管道符"|"的内容来指定,也可以使用手工输入的方式。

[root@instsvr1 ~]# mutt -help
Mutt 1.4.2.2i (2006-07-14)
usage: mutt [ -nRyzZ ] [ -e <cmd> ] [ -F <file> ] [ -m <type> ] [ -f <file> ]
       mutt [ -nx ] [ -e <cmd> ] [ -a <file> ] [ -F <file> ] [ -H <file> ] [ -i <file> ] [ -s <subj> ] [ -b <addr> ] [ -c <addr> ] <addr> [ ... ]
       mutt [ -n ] [ -e <cmd> ] [ -F <file> ] -p
       mutt -v[v]

options:
  -a <file>     attach a file to the message
  -b <address>  specify a blind carbon-copy (BCC) address
  -c <address>  specify a carbon-copy (CC) address
  -e <command>  specify a command to be executed after initialization
  -f <file>     specify which mailbox to read
  -F <file>     specify an alternate muttrc file
  -H <file>     specify a draft file to read header from
  -i <file>     specify a file which Mutt should include in the reply
  -m <type>     specify a default mailbox type
  -n            causes Mutt not to read the system Muttrc
  -p            recall a postponed message
  -R            open mailbox in read-only mode
  -s <subj>     specify a subject (must be in quotes if it has spaces)
  -v            show version and compile-time definitions
  -x            simulate the mailx send mode
  -y            select a mailbox specified in your `mailboxes' list
  -z            exit immediately if there are no messages in the mailbox
  -Z            open the first folder with new message, exit immediately if none
  -h            this help message

【中文】

   -a<文件>    在邮件中加上附加文件。
   -b<地址>    指定密件副本的收信人地址。
   -c<地址>    指定副本的收信人地址。
   -f<邮件文件>    指定要载入的邮件文件。
   -F<配置文件>    指定mutt程序的设置文件,而不读取预设的.muttrc文件。
   -h    显示帮助。
   -H<邮件草稿>    将指定的邮件草稿送出。
   -i<文件>    将指定文件插入邮件内文中。
   -m<类型>    指定预设的邮件信箱类型。
   -n    不要去读取程序培植文件(/etc/Muttrc)。
   -p    在mutt中编辑完邮件后,而不想将邮件立即送出,可将该邮件暂缓寄出。
   -R    以只读的方式开启邮件文件。
   -s<主题>    指定邮件的主题。
   -v    显示mutt的版本信息以及当初编译此文件时所给予的参数。
   -x    模拟mailx的编辑方式。
   -z    与-f参数一并使用时,若邮件文件中没有邮件即不启动mutt。



3、最后来介绍一下怎么发送html格式的邮件

mail命令只能支持text格式的邮件内容发送,如果需要发送html格式内容的邮件,那么需要使用sendmail命令或者mutt命令,下面我只介绍sendmail命令,mutt命令发送html请google

直接上脚本,不解释:

脚本1:

#!/bin/bash
#send a html-email using sendmail command
#author:mlsx mlsx(dot)xplore(at)gmail(dot)com
#license:GPL

from="my@mydomain.com"                                                            --- 指定发送者名称
subject="test html-email using mail command"                         --- 邮件标题
msgdate=`date +"%a, %e %Y %T %z"`  # Leave alone             --- 邮件日期
emailtarget="user1@163.com user2@163.com"                      --- 邮件接受者列表

daemail=$(cat <<!
Date: $msgdate
From: $from
To:$emailtarget
Subject: $subject
Mime-Version: 1.0
Content-Type: text/html; charset=gb2312                                     --- 指定邮件类型为html格式及编码为gb2312字符编码
!)

echo "$daemail" > msg.tmp
echo >>msg.tmp
cat test.html >>msg.tmp
echo  >> msg.tmp
cat msg.tmp |sendmail -t
rm -f msg.tmp


脚本2:

cat test.html |formail -I "From: root@srcb.com" -I "MIME-Version:1.0" -I "Content-type:text/html;charset=gb2312" -I "Subject:test html"|/usr/sbin/sendmail -oi user1@163.com user2@163.com

【注意】脚本2里面用到的formail命令有procmail-3.22-17.1.x86_64.rpm包提供,这是一个用来格式化邮件的工具。



总结:总的来说还是mutt比较好用一些,但是使用mutt的-e选项-e 'my_hdr content-type:text/html"'发送html邮件时总是不成功,不知道为什么!


附上Multipart Internet Mail Extensions (MIME) 的Content-Type一览 表

原:http://www.utoronto.ca/webdocs/HTMLdocs/Book/Book-3ed/appb/mimetype.html


Description of Data Content
Typical Filename Extensions


MIME type/subtype
    Text and Text-Related Types   HTML text data (RFC 1866)html htm text/htmlPlain text: documents; program listingstxt c c++ pl cc h text/plainRichtext (obsolete - replaced by text/enriched)  text/richtextStructure enhanced text(etx?) text/x-setextEnriched text markup (RFC 1896)  text/enrichedTab-separated values (tabular)(tsv?) text/tab-separated-valuesSGML documents (RFC 1874)  text/sgmlSpeech synthesis data (MVP Solutions)talk text/x-speech    Document Stylesheet Types   Cascading Stylesheetscss text/cssDSSSL-online stylesheets  application/dsssl (proposed)    Image Types   GIFgif image/gifX-Windows bitmap (b/w)xbm image/x-xbitmapX-Windows pixelmap (8-bit color)xpm image/x-xpixmapPortable Network Graphicspng image/x-pngImage Exchange Format (RFC 1314)ief image/iefJPEGjpeg jpg jpe image/jpegTIFFtiff tif image/tiffRGBrgb image/rgb   image/x-rgb Group III Fax (RFC 1494)g3f image/g3faxX Windowdump formatxwd image/x-xwindowdumpMacintosh PICT formatpict image/x-pictPPM (UNIX PPM package)ppm image/x-portable-pixmapPGM (UNIX PPM package)pgm image/x-portable-graymapPBM (UNIX PPM package)pbm image/x-portable-bitmapPNM (UNIX PPM package)pnm image/x-portable-anymapMicrosoft Windows bitmapbmp image/x-ms-bmpCMU rasterras image/x-cmu-rasterKodak Photo-CDpcd image/x-photo-cdComputer Graphics Metafilecgm image/cgmNorth Am. Presentation Layer Protocol  image/naplpsCALS Type 1 or 2mil cal image/x-calsFractal Image Format (Iterated Systems)fif image/fifQuickSilver active image (Micrografx)dsf image/x-mgx-dsfCMX vector image (Corel)cmx image/x-cmxWavelet-compressed (Summus)wi image/waveletAutoCad Drawing (SoftSource)dwg image/vnd.dwg   image/x-dwgAutoCad DXF file (SoftSource)dxf image/vnd.dxf   image/x-dxfSimple Vector Format (SoftSource)svf image/vnd.svf   also vector/x-svf    Audio/Voice/Music Related Types   "basic"audio - 8-bit u-law PCMau snd audio/basicMacintosh audio format (AIpple)aif aiff aifc audio/x-aiffMicrosoft audiowav audio/x-wavMPEG audiompa abs mpega audio/x-mpegMPEG-2 audiomp2a mpa2 audio/x-mpeg-2compressed speech (Echo Speech Corp.)es audio/echospeechToolvox speech audio (Voxware)vox audio/voxwareRapidTransit compressed audio (Fast Man)lcc application/fastmanRealaudio (Progressive Networks)ra ram application/x-pn-realaudioNIFF music notation data format  application/vnd.music-niffMIDI music datammid x-music/x-midiKoan music data (SSeyo)skp application/vnd.koan   application/x-koanSpeech synthesis data (MVP Solutions)talk text/x-speech    Video Types   MPEG videompeg mpg mpe video/mpegMPEG-2 videompv2 mp2v video/mpeg-2Macintosh Quicktimeqt mov video/quicktimeMicrosoft videoavi video/x-msvideoSGI Movie formatmovie video/x-sgi-movieVDOlive streaming video (VDOnet)vdo video/vdoVivo streaming video (Vivo software)viv video/vnd.vivo   video/vivoSpecial HTTP/Web Application Types   Proxy autoconfiguration (Netscape browsers)pac application/x-ns-proxy-autoconfigSee Chapter 6  application/x-www-form-urlencodedSee Chapter 9  application/x-www-local-execSee Chapter 9 (Netscape extension)  multipart/x-mixed-replaceSee Chapter 9 and Appendix B  multipart/form-dataNetscape Cooltalk chat data (Netscape)ice x-conference/x-cooltalkInteractive chat (Ichat)  application/x-chat    Application Types       Text-Related   PostScriptai eps ps application/postscriptMicrosoft Rich Text Formatrtf application/rtfAdobe Acrobat PDFpdf application/pdf   application/x-pdfMaker Interchange Format (FrameMaker)mif application/vnd.mif   application/x-mifTroff documentt tr roff application/x-troffTroff document with MAN macrosman application/x-troff-manTroff document with ME macrosme application/x-troff-meTroff document with MS macrosms application/x-troff-msLaTeX documentlatex application/x-latexTex/LateX documenttex application/x-texGNU TexInfo documenttexinfo texi application/x-texinfoTeX dvi formatdvi application/x-dviMacWrite document?? application/macwriteiiMS word document?? application/mswordWordPerfect 5.1 document?? application/wordperfect5.1SGML application (RFC 1874)  application/sgmlOffice Document Architectureoda application/odaEnvoy Documentevy application/envoyWang Info. Tranfer Format (Wang)  application/witaDEC Document Transfer Format (DEC)  application/dec-dxIBM Document Content Architecture (IBM)  application/dca-rft    CommonGround Digital Paper (No Hands Software)  application/commongroundFrameMaker Documents (Frame)doc fm frm frame application/vnd.framemaker   application/x-framemakerRemote printing at arbitrary printers (RFC 1486)  application/remote-printing    Archive/Compressed Archives   Gnu tar formatgtar application/x-gtar4.3BSD tar formattar application/x-tarPOSIX tar formatustar application/x-ustarOld CPIO formatbcpio application/x-bcpioPOSIX CPIO formatcpio application/x-cpioUNIX sh shell archiveshar application/x-sharDOS/PC - Pkzipped archivezip application/zipMacintosh Binhexed archivehqx application/mac-binhex40Macintosh Stuffit Archivesit sea application/x-stuffitFractal Image Formatfif application/fractalsBinary, UUencodedbin uu application/octet-streamPC executableexe application/octet-streamWAIS "sources"src wsrc application/x-wais-sourceNCSA HDF data formathdf application/hdf    Downloadable Program/Scripts   Javascript programjs ls mocha text/javascript   application/x-javascriptVBScript program  text/vbscriptUNIX bourne shell programsh application/x-shUNIX c-shell programcsh application/x-cshPerl programpl application/x-perlTcl (Tool Control Language) programtcl application/x-tclAtomicmail program scripts (obsolete)  application/atomicmailSlate documents - executable enclosures (BBN)  application/slateUndefined binary data (often executable progs)  application/octet-streamRISC OS Executable programs (ANT Limited)  application/riscos    Animation/Multimedia   Andrew Toolkit inset  application/andrew-insetFutureSplash vector animation (FutureWave)spl application/futuresplashmBED multimedia data (mBED)mbd application/mbedletMacromedia Shockwave (Macromedia)  application/x-directorSizzler real-time video/animation  application/x-spritePowerMedia multimedia (RadMedia)rad application/x-rad-powermedia    Presentation    PowerPoint presentation (Microsoft)ppz application/mspowerpointPointPlus presentation data (Net Scene)css application/x-pointplusASAP WordPower (Software Publishing Corp.)asp application/x-asapAstound Web Player multimedia data (GoldDisk)asn application/astoundSpecial Embedded Object    OLE script e.g. Visual Basic (Ncompass)axs application/x-olescriptOLE Object (Microsoft/NCompass)ods application/x-oleobjectOpenScape OLE/OCX objects (Business@Web)opp x-form/x-openscapeVisual Basic objects (Amara)wba application/x-webbasicSpecialized data entry forms (Alpha Software)frm application/x-alpha-formclient-server objects (Wayfarer Communications)wfx x-script/x-wfxclientGeneral Applications   Undefined binary data (often executable progs)  application/octet-streamCALS (U.S. D.O.D data format - RFC 1895)  application/cals-1840Pointcast news data (Pointcast)pcn application/x-pcnExcel spreadsheet (Microsoft)  application/vnd.ms-excel   application/x-msexcel   application/ms-excelPowerPoint (Microsoft)ppt application/vnd.ms-powerpoint   application/ms-powerpointMicrosoft Project (Microsoft)  application/vnd.ms-projectWorks data (Microsoft)  application/vnd.ms-worksMAPI data (Microsoft)  application/vnd.ms-tnefArtgallery data (Microsoft)  application/vnd.artgalrySourceView document (Dataware Electronics)svd application/vnd.svdTruedoc (Bitstream)  application/vnd.truedocNet Install - software install (20/20 Software)ins application/x-net-installCarbon Copy - remote control/access (Microcom)ccv application/ccvSpreadsheets (Visual Components)vts workbook/formulaoneCybercash digital money (Cybercash)  application/cybercashFormat for sending generic Macintosh files  application/applefileActive message -- connect to active mail app.  application/activemessageX.400 mail message body part (RFC 1494)  application/x400-bpUSENET news message id (RFC 1036)  application/news-message-idUSENET news message (RFC 1036)  application/news-transmission    Multipart Types (mostly email)   Messages with multiple parts  multipart/mixedMessages with multiple, alternative parts  multipart/alternativeMessage with multiple, related parts  multipart/relatedMultiple parts are digests  multipart/digestFor reporting of email status (admin.)  multipart/reportOrder of parts does not matter  multipart/parallelMacintosh file data  multipart/appledoubleAggregate messages; descriptor as header  multipart/header-setContainer for voice-mail  multipart/voice-messageHTML FORM data (see Ch. 9 and App. B)  multipart/form-dataInfinite multiparts - See Chapter 9 (Netscape)  multipart/x-mixed-replace    Message Types (mostly email)   MIME message  message/rfc822Partial message  message/partialMessage containing external references  message/external-bodyMessage containing USENET news  message/newsHTTP message  message/http    2D/3D Data/Virtual Reality Types   VRML data filewrl vrml x-world/x-vrml

(changing to model/vrml)

WIRL - VRML data (VREAM)vrw x-world/x-vreamPlay3D 3d scene data (Play3D)p3d application/x-p3dViscape Interactive 3d world data (Superscape)svr x-world/x-svrWebActive 3d data (Plastic Thought)wvr x-world/x-wvrQuickDraw3D scene data (Apple)3dmf x-world/x-3dmf    Scientific/Math/CAD Types   Chemical types -- to communicate information about chemical models  chemical/* (several subtypes)Mathematica notebookma application/mathematicaComputational meshes for numerical simulationsmsh x-model/x-mesh

(evolving to model/mesh)

Vis5D 5-dimensional datav5d application/vis5dIGES models -- CAD/CAM (CGM) dataigs application/iges

(evolving to model/iges?)

Autocad WHIP vector drawingsdwf drawing/x-dwf    
Largely Platform-Specific Types   
Silicon Graphics Specific Types   Showcase Presentationsshowcase slides sc sho show application/x-showcaseInsight Manual pagesins insight application/x-insightIris Annotator dataano application/x-annotatorDirectory Viewerdir application/x-dirviewSoftware Licenselic application/x-enterlicenseFax manager filefaxmgr application/x-fax-managerFax job data filefaxmgrjob application/x-fax-manager-jobIconBook dataicnbk application/x-iconbook?wb application/x-inpviewInstallable software in 'inst' formatinst application/x-installMail foldermail application/x-mailfolder?pp ppages application/x-ppagesData for printer (via lpr)sgi-lpr application/x-sgi-lprSoftware in 'tardist' formattardist application/x-tardistSoftware in compressed 'tardist' formatztardist application/x-ztardistWingZ spreadsheetwkz application/x-wingzOpen Inventor 3-D scenesiv graphics/x-inventor






原创粉丝点击