first,Verification module is or not install.
[oracle@datahouse report]$ python
Python 2.7.12 |Anaconda 4.2.0 (64-bit)| (default, Jul 2 2016, 17:42:40)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org
>>> import smtplib
>>> dir(smtplib)
['CRLF', 'LMTP', 'LMTP_PORT', 'OLDSTYLE_AUTH', 'SMTP', 'SMTPAuthenticationError', 'SMTPConnectError', 'SMTPDataError', 'SMTPException', 'SMTPHeloError', 'SMTPRecipientsRefused', 'SMTPResponseException', 'SMTPSenderRefused', 'SMTPServerDisconnected', 'SMTP_PORT', 'SMTP_SSL', 'SMTP_SSL_PORT', 'SSLFakeFile', '_MAXLINE', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_addr_only', '_have_ssl', 'base64', 'email', 'encode_base64', 'hmac', 'quoteaddr', 'quotedata', 're', 'socket', 'ssl', 'stderr']
>>> import email
>>> dir(email)
['Charset', 'Encoders', 'Errors', 'FeedParser', 'Generator', 'Header', 'Iterators', 'LazyImporter', 'MIMEAudio', 'MIMEBase', 'MIMEImage', 'MIMEMessage', 'MIMEMultipart', 'MIMENonMultipart', 'MIMEText', 'Message', 'Parser', 'Utils', '_LOWERNAMES', '_MIMENAMES', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__version__', '_name', '_parseaddr', 'base64MIME', 'base64mime', 'email', 'encoders', 'importer', 'message_from_file', 'message_from_string', 'mime', 'quopriMIME', 'sys', 'utils']
>>>
implementation mail detail informations
[oracle@datahouse ~]$ more mail.py
#/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import sys
import time
import email
import datetime
import smtplib
import urllib2
import sys
import socket
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
class Mail(object):
"""邮件"""
host = 'mail.163.com.cn'
port = ''
user = ''
psd = ''
fromAdd = ''
toAdd = []
subject = ''
plainText = ''
htmlText = '''<html>
<head><title>''' + subject + '''</title></HEAD>
<body><span style='cursor=hand'><B>HTML文本</B></span></html>
'''
def __init__(self, host='mail.163.com.cn', port='25', user='it', psd='xxxxx', mailFrom='it@163.com.cn', mailTo=['trsenzhang@163.com.cn']):
ipadd=socket.gethostbyname(host)
self.port = port
self.host = host
self.user = user
self.psd = psd
self.fromAdd = mailFrom
self.toAdds = mailTo
self.port = port
def sendMsg(self, subject, msg, attachment_file=None, _login='false'):
server = self.host
user = self.user
psd = self.psd
mailto = ';'.join(self.toAdds)
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = subject
msgRoot['From'] = '系统监测<' + self.fromAdd + '>'
msgRoot['To'] = mailto
msgRoot.preamble = 'This is a multi-part message in MIME format.'
#Encapsulate the plain and HTML versions of the message body in an
#'alternative' part, so message agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
#Define the text informations
msgText = MIMEText(msg, 'plain', 'gb2312')
msgAlternative.attach(msgText)
contype = 'application/octet-stream'
maintype, subtype = contype.split('/', 1)
print attachment_file
if attachment_file:
#设置附件头
for fn in attachment_file:
data = open(fn,'rb')
file_msg = email.MIMEBase.MIMEBase(maintype, subtype)
file_msg.set_payload(data.read())
data.close()
bn=os.path.basename(fn)
file_msg.add_header('Content-Disposition','attachment',filename=bn)
msgAlternative.attach(file_msg)
email.Encoders.encode_base64(file_msg)
#发送邮件
try:
smtp = smtplib.SMTP()
smtp.connect(server, self.port)
if _login == 'true':
smtp.starttls()
smtp.login(user, psd)
smtp.sendmail(self.fromAdd, self.toAdds, msgRoot.as_string())
smtp.quit()
smtp.close()
except Exception,e :
return
return
def sendEmail(self, authInfo, fromAdd, toAdd, subject, plainText, htmlText):
strFrom = fromAdd
strTo = ', '.join(toAdd)
server = authInfo.get('server')
user = authInfo.get('user')
passwd = authInfo.get('password')
if not (server and user and passwd) :
return
#设定root信息
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = subject
msgRoot['From'] = strFrom
msgRoot['To'] = strTo
#Encapsulate the plain and HTML versions of the message body in an
#'alternative' part, so message agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
#设定纯文本信息
msgText = MIMEText(plainText, 'plain', 'gb2312')
msgAlternative.attach(msgText)
#发送邮件
smtp = smtplib.SMTP()
#设定调试级别,依情况而定
#smtp.set_debuglevel(1)
smtp.connect(server)
#smtp.login(user, passwd)
smtp.sendmail(strFrom, strTo, msgRoot.as_string())
smtp.quit()
return
execute the scripts
[oracle@datahouse ~]$ more t1.py
#!/bin/env python
#coding:utf-8
import sys
import os
import socket
from mail import Mail
from utility import logger
import time
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.ZHS16GBK'
#mail function
def mail(logfile):
mail_to=['trsenzhang@163.com.cn']
port="25"
m=Mail(port=port,mailTo=mail_to)
try:
subject='数据仓库orders表加工'
content=open(logfile,'r').read()
m.sendMsg(subject,content)
except:
return
if __name__ == '__main__':
# mail report
logfile= '/report/log/'+'orders_'+time.strftime("%Y%m%d",time.localtime())+'.log'
f=open(logfile,'w')
f.write('orders在:'+time.strftime("%Y:%m:%d %H:%M:%S",time.localtime())+' 完成CSV文件转换\n')
f.close()
mail(logfile)
Any error
Don't config the /etc/resolv.conf to DNS
[oracle@datahouse report]$ python t1.py
Traceback (most recent call last):
File "t1.py", line 18, in <module>
ipadd=socket.gethostbyname('mail.163.com.cn')
socket.gaierror: [Errno -3] Temporary failure in name resolution
solution:
Config the /etc/resolv.conf