Linux mail/mailx利用Office365 SMTP发送邮件

先用一行命令测试下:

$ echo "This is the message body" | mail -r "[email protected]" -s "This is the subject" -S smtp="smtp.office365.com:587" -S smtp-use-starttls -S smtp-auth=login -S smtp-auth-user="[email protected]" -S smtp-auth-password="abc123" -S ssl-verify=ignore -S nss-config-dir=~/.mozilla/firefox/default.clm [email protected]

说明: 

-r the From address

nss-config-dir A directory that contains the files certN.db to retrieve certificates, keyN.db to retrieve private keys, and secmod.db, where N is a digit. Firefox的profile中包含这三个文件,先临时使用一下。

运行上面的命令能发送邮件,但报以下错误Error in certificate: Peer's certificate issuer is not recognized.

先不管这个错误,把以上参数配置到/etc/mail.rc的末尾,如下:

set [email protected]

set smtp=smtp.office365.com:587

set smtp-auth=login

set [email protected]

set smtp-auth-password=abc123

set smtp-use-starttls

set ssl-verify=ignore

set nss-config-dir=~/.mozilla/firefox/default.clm

再次运行如下命令测试:

$ echo "This is the message body" | mail  -s "This is the subject" [email protected]

执行结果应与上次相同。

现在处理上面出现的异常,原因是尚未导入office365的证书。之前使用的是firefox的证书配置文件,虽然mail仅读取不会修改其内容,但当其被firefox修改时,会导致错误发生。因此需要重建一个目录,将cert8.db、key3.db、secmod.db三个文件拷贝出来。

也可以使用certutil重新创建这些文件,命令如下:

$ mkdir ~/.certs

$ certutil -N -d ~/.certs
Enter a password which will be used to encrypt your keys.
The password should be at least 8 characters long,
and should contain at least one non-alphabetic character.
 
Enter new password:
Re-enter password:

获取office 365证书:

$ echo -n | openssl s_client -starttls smtp -crlf -connect smtp.office365.com:587 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ~/.certs/365.crt

导入证书:

$ certutil -A -n "Office 365 Authority" -t "C,P,T" -d ~/.certs -i ~/.certs/365.crt

说明:

-t trustargs

Specify the trust attributes to modify in an existing certificate or to apply to a certificate when creating it or adding it to a database. There are three available trust categories for each certificate, expressed in the order SSL, email, object signing for each trust setting. In each category position, use none, any, or all of the attribute codes:

• p - Valid peer

• P - Trusted peer (implies p)

• c - Valid CA

• C - Trusted CA (implies c)

• T - trusted CA for client authentication (ssl server only)
The attribute codes for the categories are separated by commas, and the entire set of attributes enclosed by quotation marks.

检查证书:

$ certutil -L -d ~/.certs

修改配置

set nss-config-dir=~/.certs

再次执行发送邮件命令,完全正常了。

Linux mailx command

certutil (1) - Linux Man Pages

9 mail/mailx command examples to send emails from command line on Linux

猜你喜欢

转载自billben.iteye.com/blog/2404211
今日推荐