1. 程式人生 > >通過郵件發送賬單詳情

通過郵件發送賬單詳情

== 資源 login ext -s emp med col con

1、為了方便財務部分查看個賬戶支出詳情,通過計劃任務每天發送賬單情況

python 代碼如下:

# coding:utf-8

from django.db.models import Q
from jumpserver.api import *
from jumpserver.models import Setting
from django.http import HttpResponse,StreamingHttpResponse
from django.shortcuts import render,render_to_response
from jcloud.aws_iam_scan import *
from jcloud.aws_service_san import *
from jcloud.forms import Aws_monitor_userForm
from jcloud.models import *
import json
import django.utils.timezone as timezone
import time
from datetime import date, timedelta
import boto3
import zipfile
import zlib
import os
import csv
import codecs
import re
import sys
reload(sys)
sys.setdefaultencoding(‘utf8‘)

import smtplib
from email.mime.text import MIMEText
from email.header import Header
from django.template import loader
from pprint import pprint
def sendmail():
    def sendaction(html):#定義發送方法
        HOST = "smtp.exmail.qq.com"
        TO = "email"
        FROM = "email"
        msg = MIMEText(html_content,"html","utf-8")
        msg[‘Subject‘] = u‘AWS雲主機賬單‘
        msg[‘From‘]=FROM
        msg[‘To‘]=TO

        try:
            server = smtplib.SMTP()
            server.connect(HOST,"587")
            server.starttls()
            server.login("user","password")
            server.sendmail(FROM, TO, msg.as_string())
            server.quit()
            print "郵件發送成功!"
        except Exception, e:
            print "失敗:"+str(e)

    def rescount(accout_tag):#查詢賬戶數量和服務分類
        aws_volumes_list   = Aws_volumes.objects.filter(account_tag=accout_tag)
        aws_snapshots_list = Aws_snapshots.objects.filter(account_tag=accout_tag)
        aws_s3_list        = Aws_s3.objects.filter(account_tag=accout_tag)
        aws_ec2_list       = Aws_ec2.objects.filter(account_tag=accout_tag)
        aws_rds_list       = Aws_rds.objects.filter(account_tag=accout_tag)

        aws_detail         = Aws_detail_price.objects.filter(account_tag=accout_tag)

        ddict = {}
        for d in aws_detail:#遍歷所有收費項目,分別累加不同服務價格
            ddict[d.service_id] = d.aws_price

        list_volume = []#卷使用價格
        t_volume = float(0)
        for volume in aws_volumes_list:
            if volume.VolumeId in ddict.keys():
                t_volume = t_volume + float(ddict[volume.VolumeId])
                del(ddict[volume.VolumeId])
        list_volume.append(‘volume‘)
        list_volume.append(len(aws_volumes_list))
        list_volume.append(t_volume)
        # print list_volume

        list_snapshots = []#快照價格
        t_snapshots = float(0)
        for key in ddict.keys():
            for snapshots in aws_snapshots_list:
                if re.search(snapshots.SnapshotId,key):
                    t_snapshots = t_snapshots + float(ddict[key])
                    del(ddict[key])

        list_snapshots.append(‘snapshots‘)
        list_snapshots.append(len(aws_snapshots_list))
        list_snapshots.append(t_snapshots)
        # print list_snapshots

        list_s3 = []#s3價格
        t_s3 = float(0)
        for s3 in aws_s3_list:
            if s3.Name in ddict.keys():
                t_s3 = t_s3 + float(ddict[s3.Name])
                del(ddict[s3.Name])
        list_s3.append(‘s3‘)
        list_s3.append(len(aws_s3_list))
        list_s3.append(t_s3)
        # print list_s3

        list_ec2 = []#ec2價格
        t_ec2 = float(0)
        for ec2 in aws_ec2_list:
            if ec2.InstanceId in ddict.keys():
                t_ec2 = t_ec2 + float(ddict[ec2.InstanceId])
                del(ddict[ec2.InstanceId])
        list_ec2.append(‘ec2‘)
        list_ec2.append(len(aws_ec2_list))
        list_ec2.append(t_ec2)
        # print list_ec2

        list_rds = []#rds 價格
        t_rds = float(0)
        for rds in aws_rds_list:
            if rds.DBInstanceArn in ddict.keys():
                t_rds = t_rds + float(ddict[rds.DBInstanceArn])
                del(ddict[rds.DBInstanceArn])
        list_rds.append(‘rds‘)
        list_rds.append(len(aws_rds_list))
        list_rds.append(t_rds)
        # print list_rds

        list_other = []#其他價格
        o_price = float(0)
        for o in ddict.keys():
            o_price = o_price + float(ddict[o])
        list_other.append(‘Others‘)
        list_other.append(len(ddict))
        list_other.append(o_price)
        # print list_other

        tmp_list = []
        tmp2_list = []
        sprice = float(0)
        for l in [list_ec2,list_volume,list_s3,list_rds,list_snapshots,list_other]:
            sprice = sprice + l[2]
            tmp_list.append(l)
        tmp2_list.append(tmp_list)
        tmp2_list.append(dict_tag[accout_tag])
        tmp2_list.append(sprice)
        if accout_tag == 1:
            tmp2_list.append("RMB")
        else:
            tmp2_list.append("Dollar")

        list_res.append(tmp2_list)
    dict_tag = {}#區分不同賬戶資源
    dict_tag[1] = ‘中國:ptmind‘
    dict_tag[2] = ‘海外:administrator‘

    list_res = []
    for tag in dict_tag.keys():
        rescount(tag)
    ttime = time.strftime(‘%m‘,time.localtime(time.time()))
    html_content = loader.render_to_string(‘jcloud/sendmail.html‘,locals())
    # print html_content
    # return my_render(‘jcloud/sendmail.html‘, locals(), request)
    # print html_content 
    sendaction(html_content)

發送頁面sendmail.html內容如下:


<style type="text/css">
#定義內容寬度為400px,目的便於手機瀏覽
#content{
    margin: 20px auto;
    width: 400px;
}

#content h1{
    text-align: center;
    font-size: 30px;
}
.div_tables{
    width: 340px;
    margin: 20px auto;
    background: white;
}

.title_top{
    font-size: 16px;
    text-align: left;
    color: black;
    height: 15px;
    line-height: 15px;
}
.price_bottom{
    margin: 0 auto;
    text-align: right;
    font-size: 14px;
    color: black;
    height: 10px;
    line-height: 25px;
    height: 25px;
    color: red;
}

.first_col{

}

.t1 td:first-child{
    width: 40px;
    height: 30px;
}

.t1 td{
    width: 100px;
    font-size: 18px;
    line-height: 20px;
    height: 20px;
}

.t1 td:last-child{
    width: 100px;
    text-align: right;
}
.t1 hr{
    margin: 5px auto;
    border-bottom: 2px solid black !important;
}

.ec2{
    height: 20px;
    width: 20px;
    background-color: #4497d1;
}

.volume{
    height: 20px;
    width: 20px;
    background-color: #779b3e;
}

.s3{
    height: 20px;
    width: 20px;
    background-color: #779b3e;
}
.snapshots{
    height: 20px;
    width: 20px;
    background-color: #fa832b;
}

.rds{
    height: 20px;
    width: 20px;
    background-color: #c0422c;
}

.Others{
    height: 20px;
    width: 20px;
    background-color: #929292;
}
</style>
<div id = "content" >
    <h1>{{ ttime }}月 AWS 賬單</h1>
        #遍歷後臺渲染內容
        {% for t in list_res %}
            <div class="div_tables">
                <table class = "t1">              
                        <head>
                            <tr>
                                <th colspan="4"><p class="title_top">{{ t.1 }}</p><hr /></th>                            
                            </tr>
                        </head>   
                    {% for i in t.0 %}
                        <tr>
                           <td><div class = ‘{{ i.0 }}‘></div></td>
                           <td>{{ i.0 }}</td>
                           <td>{{ i.1 }}</td>
                           <td>{{ i.2 }}</td>
                        </tr>
                    {% endfor %}
                    <tr>                            
                        <th colspan="4"><hr /><p class="price_bottom">{{ t.3 }}:?{{ t.2 }}</p></th>                            
                    </tr>                    
                </table>
            </div>
        {% endfor %}
</div>

最後展示效果如下:
技術分享圖片

通過郵件發送賬單詳情