欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  网络运营

linux脚本实现自动发送和收取邮件的设置方法

程序员文章站 2022-10-14 08:36:38
1. 命令行模式下的发送邮件 1.1 安装sendemail 2.2 使用sendemail和举例 2. 命令行模式下的收取邮件 2.1 安装getmail4 2.2 配置...
1. 命令行模式下的发送邮件
1.1 安装sendemail
2.2 使用sendemail和举例

2. 命令行模式下的收取邮件
2.1 安装getmail4
2.2 配置getmail4和简单举例
2.3 用munpack从邮件中抽取附件

1. 命令行模式下的发送邮件

1.1 安装sendemail
在ubuntu下可以用新立得软件包管理器搜索安装,或者在终端运行:
sudo apt-get install sendemail
建议在安装前先安装另外两个包:libio-socket-ssl-perl, libnet-ssleay-perl

2.2 使用sendemail和举例

如果你想用你的邮箱christ@gmail.com发送邮件到buddha@qq.com,在终端输入:
sendemail -s smtp.gmail.com -f christ@gmail.com -t buddha@qq.com -u hello -m "a hello from christans to buddhists via gmail" -xu christ -xp password -o tls=auto

解释:
-s smtp.gmail.com 指定服务器域名,邮件发送一般通过smtp协议实现,其域名一般为smtp.***.com,比如qq邮箱的服务器为smtp.qq.com,163邮箱则为smtp.163.com
-f christ@gmail.com指定发送邮箱地址
-t buddha@qq.com 指定目的邮箱地址
-u hello 邮件标题
-m "a hello from christans to buddhists via gmail" 邮件正文,较长的正文可以先存在文本文件中,不妨命名为mail.txt,然后换用-o message-file=mail.txt
-xu christ 指定邮箱用户名,即邮箱地址@之前的部分
-xp password 指定发送邮箱的密码
-o tls=auto 加密方式在none, tls, ssl中自动选择
如果想在邮件中粘帖附件
-a attachment_file1 attachment_file2 attachment_file3

2. 命令行模式下的收取邮件

通过邮件客户端收取email邮件主要有两种方式:pop3和imap,邮件客户端通过pop3下载服务器上的邮件,但是imap默认只下载邮件的主题。基于命令行方式自动化的意义,采用pop3更合适。

2.1 安装getmail4

在ubuntu下可以用新立得软件包管理器搜索安装,或者
sudo apt-get install getmail4

2.2 配置getmail4和简单举例

安装完毕后在终端执行一下命令
复制代码 代码如下:

cd ~
mkdir .getmail
cd .getmail
mkdir maildir
cd maildir
mkdir new cur tmp


后在 .getmail/下建立一个配置文件,如果这个配置文件是为收取buddha@qq.com这个邮箱配置的,不妨命名为getmailrc.buddha,然后编辑该文件,#后是注释:

复制代码 代码如下:

# this is a configuration file for buddha@qq.com
[retriever]
type = simplepop3retriever
server = pop.qq.com #如果是gmail则改为pop.gmail.com
username = budda
password = password

[destination]
type = maildir
path = ~/.getmail/maildir/ #就是刚才在~/.getmail/建立的目录,注意该目录下一定要有new,cur,tmp这三个子目录

[options]
read_all = false #只接受以前没有收取的邮件,如果改成true则收取邮箱中所有邮件
delete = false #下载邮件后不在服务器上删除该邮件,如果改成true则删除

# configuration file ends here
编辑好了之后在终端运行:
getmail --rcfile=getmailrc.buddha

getmail会自动收取邮件,下载的邮件会保存在~/.getmail/maildir/new/下。

2.3 用munpack从邮件中抽取附件

邮件正文和附件是作为一个整体文件被保存的,附件以mime格式附着在整体文件最后,必须用程序抽取出来。
在ubuntu下可以用新立得软件包管理器搜索安装mpack,或者 sudo apt-get install mpack
在终端中运行:munpack mail_file
程序会自动识别附件并抽取出来。