linux从命令行发送邮件

来源:互联网 发布:淘宝如何处理中差评 编辑:程序博客网 时间:2024/06/05 20:12

ubuntu server 14.04 从命令行发邮件

安装mailutils

sudo apt-get install mailutils

接下来进行默认安装就行了。Postfix Configuration
这里写图片描述

这里写图片描述

这里写图片描述
需要记住这里的System mail name,后面会用到。

发送邮件

  1. 用一行命令发送邮件
    给邮箱example@qq.com(改成你自己要发送的邮箱)发封邮件。邮件主题为Test email from ubuntu server!,内容为Here is the message body.

    • mail -s "Test email from ubuntu server!" example@qq.com <<< 'Here is the message body.'

    • echo 'Here is the message body.' | mail -s "Test email from ubuntu server!" example@qq.com

    以上两条命令可以得到同样的效果。其中,-s 参数指定邮件的主题。
    运行以上命令后,去邮箱(example@qq.com)里查看是否收到邮件。如果收件箱里没有,可能在垃圾邮件里。

  2. 使用mail的命令提示发送邮件
    peter@qq.com 发送邮件,并抄送给john@qq.com。邮件主题为Ubuntu Test,内容为Merry christmas

    • mail -s 'Test Subject' peter@qq.com

    输入该命令后回车,提示Cc:,这时输入抄送邮件地址john@qq.com,然后回车。
    继续输入邮件正文内容Merry christmas,正文输入结束后,按Ctrl-D 结束输入并发送邮件。

  3. 从文件中读取邮件内容并发送
    给邮箱example@qq.com发送邮件,邮件主题为Text message,邮件内容为/home/user/message.txt中的内容 。

    • mail -s 'Text message' example@qq.com < /home/user/message.txt
  4. 抄送与密件抄送
    user1@qq.com发送邮件 ,并抄送给user2@qq.com,并密件抄送给user3@qq.com

    • mail -s 'Subject' user1@qq.com -c user2@qq.com -b user3@qq.com < message.txt

    -c表示抄送 ,-b表示密件抄送 。-c: carbon copy, -b: blind carbon copy
    [貌似没有这两个参数了。]

  5. 给多个邮箱发送邮件

    • mail -s 'Subject' user1@qq.com,user2@qq.com,user3@qq.com < message.txt
  6. 指定发件人姓名和地址

    • echo "This is the message body" | mail -s "subject" user@qq.com -aFrom:sender@qq.com
      使用-a参数追加邮件头信息,用来指定发件人姓名和地址。
      或者
    • echo "This is the message body" | mail -s "subject" user@qq.com -aFrom:John\<john@qq.com\>
  7. 给本机的其他用户发送邮件

    • mail -s "hello, this is a test!" username
    • mail -s "hello, this is a test!" username@ubuntu
      这两种方法等价,第二种中的ubuntu是当前系统的主机名(hostname),见安装部分的最后一张图,系统邮件名默认的是主机名,也是ubuntu

添加附件

echo "This is the message body" | mail -s "subject" user@qq.com -A /path/to/attached_file

使用-A参数为邮件添加附件。

或者使用另一个命令行工具–Mutt

-> 安装

 sudo apt-get install mutt

-> 使用

  • 发送简单邮件
    echo "This is a mutt test" | mutt -s "This is mutts subject" example@qq.com
  • 发送附件邮件:
    mutt -s "Subject" -a /path/to/file_to_attached -- example@qq.com < /home/user/mailcontent.txt
    -a参数添加附件(attach),后面跟附件所在的路径;mailcontent.txt是邮件正文内容。
    注意:附件文件和收件人之间需要使用--分隔。

shell脚本发送邮件

写一个shell脚本将硬盘使用情况发送到邮箱。使用du -sh查看硬盘使用情况。

#!/bin/bash#filename: report_disk_usage_to_email.shdu -sh | mail -s "disk usage report" user@yourmaildomain.com

在第一部分–[安装mailutils]中的第三个图中可以看到,我的yourmaildomain.comubuntu

保存后退出编辑,然后运行该脚本,命令为:sh report_disk_usage_to_email.sh

查看邮件

查看邮件直接在命令行里输入mail就列出了所有的邮件状态, 如图所示。如果没有未读邮件,则返回No mail for user
这里写图片描述

在第三行显示有7封邮件,其中3封未读。第二列是邮件编号,最后一列是邮件主题,中间是收件日期。最后一行`?`提示符表示等待输入命令。输入邮件编号,回车后就可以打开该邮件进行阅读。输入`z`回车后退后邮件列表。输入`q`回车后退出。

Reference

Linux mail command examples – send mails from command line

0 0