阿里云ECS默认禁用25端口导致发邮件失败。
方法一:
使用shell脚本发送邮件,需要配置mailx
1、安装软件
yum install mailx
2、配置
vim /etc/mail.rc在文件最后加上如下内容:
set smtp=smtps://smtp.exmail.qq.com:465 #邮箱服务器地址
set from=xxxx@xxx.com #发送邮件的来源
set smtp-auth-user=xxxx@xxx.com #用户名
set smtp-auth-password=xxxx #密码
set nss-config-dir=/etc/pki/nssdb/ #证书位置
set ssl-verify=ignore
set smtp-auth=login
3、配置证书
mkdir -p /etc/pki/nssdb/
cd /etc/pki/nssdb
#生成证书
echo -n | openssl s_client -connect smtp.qq.com:465 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > /etc/pki/nssdb/qq.crt
certutil -A -n "GeoTrust SSL CA" -t "C,," -d /etc/pki/nssdb/ -i /etc/pki/nssdb/qq.crt
certutil -A -n "GeoTrust Global CA" -t "C,," -d /etc/pki/nssdb/ -i /etc/pki/nssdb/qq.crt
certutil -L -d /etc/pki/nssdb/
certutil -A -n "GeoTrust SSL CA - G3" -t "Pu,Pu,Pu" -d ./ -i qq.crt #认证
4、测试发送邮件
echo "this email come from centos"|mail -v -s "zabbix" xxx@xxx.com
告警邮件使用的shell脚本:
#!/bin/bash
#send mail
messages=`echo $3 | tr '\r\n' '\n'`
subject=`echo $2 | tr '\r\n' '\n'`
echo "${messages}" | mail -v -s "${subject}" $1 >>/tmp/mailx.log 2>&1
方法二:
直接使用py脚本发送邮件,使用ssl的465端口,简单快捷。
#!/bin/env python
#coding:utf8
import smtplib
from email.mime.text import MIMEText
from email.utils import parseaddr,formataddr
from email.header import Header
import sys
def _format_addr(s):
name,addr = parseaddr(s)
#将邮件的name转换成utf-8格式,addr如果是unicode,则转换utf-8输出,否则直接输出addr
return formataddr((Header(name,'utf-8').encode(),addr.encode("utf-8") if isinstance(addr,unicode) else addr))
def send_mail(to_list,subject,content):
fromaddr = "caibs@xmpaoyou.com"
msg = MIMEText(content, 'plain', 'utf-8')
msg['Subject'] = subject
msg['From'] = _format_addr(u'线上监控平台告警<%s>'%fromaddr)
msg['to'] = to_list
try:
server = smtplib.SMTP_SSL(mail_host,465)
server.login(mail_user,mail_pass)
server.sendmail(fromaddr,to_list,msg.as_string())
server.close()
return True
except Exception,e:
print str(e)
return False
if __name__ == "__main__":
#smtp信息
mail_host = 'smtp.exmail.qq.com'
mail_port = '465'
mail_user = 'ca'
mail_pass = 'Cb'
send_mail(sys.argv[1], sys.argv[2], sys.argv[3])
告警邮件内容
参考链接: