python实现发送邮件功能

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python实现发送邮件功能相关的知识,希望对你有一定的参考价值。

前一段时间实现了一个python脚本发送邮件的功能,该脚本是借用smtp服务器发送邮件,邮件以附件的形式发出,如果要添加正文,修改添加即可。

#!/usr/bin/env python
#coding: utf-8

import smtplib, re, sys, os
import xlwt
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage


def chuli_data(filepath):
    list1 = []
    with open(filepath) as fobj:
        for line in fobj:
            if re.match(".*\"_source\".*",line):
                list1.append([])
            if re.match(".*\"@timestamp\".*",line):
                tmp_value = re.findall(".*\"@timestamp\" *: *\"(.*)\" *",line)
                list1[-1].append(tmp_value[0])
            if re.match(".*\"servicetype\".*",line):
                tmp_value = re.findall(".*\"servicetype\" *: *\"(.*)\" *",line)
                list1[-1].append(tmp_value[0])
            if re.match(".*\"source\".*",line):
                tmp_value = re.findall(".*\"source\" *: *\"(.*)\" *",line)
                list1[-1].append(tmp_value[0])
            if re.match(".*\"logmsg\".*",line):
                tmp_value = re.findall(".*\"logmsg\" *: *\"(.*)\" *",line)
                list1[-1].append(tmp_value[0])
    for ele in list1:
        print ele
    return list1

def trans(str1):
    upperlist = string.uppercase
    str1 = int(str1)
    if str1 < 26:
        trans_str = upperlist[str1]
    else:
        par = int(str1/26)
        sub = str1 % 26
        trans_str = upperlist[sub]
        trans_str = trans(par) + trans_str
    return trans_str
        
def rewrite_xml(list1):
    wb = xlwt.Workbook()
    sheet = wb.add_sheet(error日志)
    ws = wb.active
    col_num = 1
    for row in list1:
        row_num = 0
        for col in row:
            ws[trans(row_num)+str(col_num)] = col
            row_num += 1
        col_num += 1
    wb.save("/tmp/tmp.xlsx")
    return True

def send_email(config_file,FROM,TO,xlsxfile_list,email_password):
    location_name="unknown"
    SUBJECT="error日志"
    with open(config_file) as fobj:
        for line in fobj:
            if re.match("<reports_subject>.*</reports_subject>",line):
                SUBJECT = re.search("<reports_subject>(.*)</reports_subject>",line).groups()[0]
                location_name = re.split("Scarlet",SUBJECT)[0]
                break
    location_name = "[%s]" % location_name.decode(utf-8)
    HOST = "smtp.ipanel.cn"
    SUBJECT = SUBJECT.decode(utf-8)
    missfile_list = []
    errfile_list = []
    inscribe = """<p>personal infomation<br>
your own description<br></p>"""

    for  file in xlsxfile_list:
        if not os.path.isfile(file):
            missfile_list.append(os.path.basename(file))

    if missfile_list:
        mail_head = """All:<br>
    &nbsp;&nbsp;&nbsp;&nbsp;附件是今日的errlog,请及时查收<br>
    &nbsp;&nbsp;&nbsp;&nbsp;此邮件为系统自动发送,请勿回复<br>
    <br>""" % ", ".join(missfile_list)
    else:
        mail_head = """<br>"""
    
    msg = MIMEMultipart(related)
    n = 1
    contents = "<font color=black>%s</font><br>" % mail_head
    for pngfile in pngfile_list:
        try:
            msg.attach(addimg(pngfile,"daily"+str(n)))
            contents += "<img src=\"cid:daily%s\" border=\"1\">" % n
            if n % 2 == 0:
                contents += "<br><br>"
        except Exception,e:
            errfile_list.append(os.path.basename(pngfile))
        finally:
            n += 1
    contents += inscribe
    msgtext = MIMEText(contents,"html","utf-8")
    msg.attach(msgtext)

    try:
        attach1 = MIMEText(open(xlsxfile_list[0],"rb").read(), "base64", "UTF-8")
        time_tag = "-".join(re.split("[_.]",xlsxfile_list[0])[-3:-1])
        attach1["Content-Type"] = "application/octet-stream"
        attach1["Content-Disposition"] = "attachment; filename=\"%s error日志 %s.xlsx\"" % (location_name.encode(utf-8),time_tag)
    except Exception,e:
        errfile_list.append(os.path.basename(xlsxfile_list[0]))    
        
    msg.attach(attach1)
    msg[Subject] = SUBJECT
    msg[From] = FROM
    msg[To] = ";".join(TO)

    try:
        server = smtplib.SMTP()
        server.connect(HOST,"25")
        server.login("[email protected]",email_password)
        server.sendmail(FROM, TO, msg.as_string())
        server.quit()
        print "邮件发送成功!"
        return True
    except Exception, e:
        print "失败:"+str(e)
        return False
        

if __name__ == __main__:
    config_file = "/opt/Scarlet/elkerrlog/monitor_elk.conf"
    FROM = "[email protected]"
    TO = ["[email protected]"]
    FILELOG = "logfile.`date +%Y%m%d`"
    xlsxfile_list = [r"/opt/Scarlet/elkerrlog/$FILELOG"]
    email_password = "Scarlet_password"
    list1 = chuli_data(xlsxfile_list[0])
    rewrite_xml(list1)
    tmp_result = send_email(config_file,FROM,TO,/tmp/tmp.xlsx,email_password)
    if not tmp_result:
        sys.exit(1)
    sys.exit(0)

 

以上是关于python实现发送邮件功能的主要内容,如果未能解决你的问题,请参考以下文章

Python用20行代码实现完整邮件功能 [完整代码+建议收藏]

Github 大牛封装 Python 代码,实现自动发送邮件只需三行代码

Python用20行代码实现完整邮件功能 [完整代码+建议收藏]

Python邮件发送源码

python实现发送邮件功能

Python django实现简单的邮件系统发送邮件功能