Python 發送郵件 and 編輯Excel


記錄一下Python 發送郵件的代碼,這是半年前寫的,不知道現在有什么類庫的改動。

 

類庫

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import datetime
 
def SendEmail(self,SendEmailExcelUrl,ProjectName):
       
        sender ='發送人郵箱'
        senderPwd =os.environ.get('EmailPassword') #郵箱密碼我這里是放在環境變量中了(Win)
        receivers ='123@123.com,123@123.com' #接收人郵箱
        #create a Instance
        message = MIMEMultipart()
        message['From'] = Header("發送人", 'utf-8')
        message['To'] =  Header("郵件內容標題", 'utf-8')
        subject = '郵件標題’
        message['Subject'] = Header(subject, 'utf-8')
        #Message body content
        message.attach(MIMEText(' Dear All, \n\n ××× \n\n Regards, \n ××××××× ', 'plain', 'utf-8'))
        #Send xlsx file 
        att = MIMEText(open(SendEmailExcelUrl, 'rb').read(), 'base64', 'utf-8')
        att["Content-Type"] = 'application/octet-stream'
        #Here you can rename the attachments in the message.
        att["Content-Disposition"] = 'attachment; filename="{}.xlsx"'.format(ProjectName)
        message.attach(att)
        try:
            smtpObj = smtplib.SMTP('代理服務器地址','代理服務器端口')
            smtpObj.starttls()
            smtpObj.login(sender, senderPwd)#代理服務器帳號密碼驗證
            smtpObj.sendmail(sender, receivers, message.as_string())
            #terminating the session
            smtpObj.quit()
            print("Send email successful")
        except  smtplib.SMTPException as e:
            print(e.__doc__,datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
            print(e.__context__,datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

 

下面是編輯excel 僅僅用於記錄

  python編輯excel 還是比較坑的,個人觀點。但是我是調用一個接口,該接口返回excel,該excel的樣式什么的都有,如果我直接進行保存這樣沒問題,但是我需要對其加一列然后在保存excel就被破壞了,后來了解到目前該類庫對樣式的編輯支持的還不是很好

 

import xlrd
import xlwt
from openpyxl import Workbook ,load_workbook

 

    def CreateCoreExcel(self,SendEmailExcelUrl,ApiSaveExcelSaveUrl):
        projectConfigJson=self.getProductfigJson()['Core']
        Group= projectConfigJson['Group']
        wb = load_workbook(ApiSaveExcelSaveUrl)
        ws = wb['Vulnerabilities']
        ws.insert_cols(2)
        ws.insert_cols(3)
        for index, row in enumerate(ws.rows):
            if index == 0:
                row[1].value='Group'
                row[2].value='ServiceName'
            else:
                values= row[22].value
                validationValues=True
                try:
                    values.split('\\')
                except Exception as e:
                    print(e.__doc__,datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                    print(e.__context__,datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                    validationValues=False
                    print("values not is path values:{}, datetime:{} ".format(values,datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
                if validationValues == True:
                    strlist = values.split('\\')
                    serviceName=strlist[3]
                    groupName=""
                    if serviceName in Group['1']:
                        groupName="1"
                    elif serviceName in Group['2']:
                        groupName="2"
                    elif serviceName in Group['3']:
                        groupName="3"
                    else:
                        groupName="OtherGroup"
                    row[1].value=groupName
                    row[2].value=serviceName
                else :
                     row[1].value="N/A"
                     row[2].value="N/A"
        content = []
        index = 1
        for i in range(2,ws.max_row+2): 
            contentJson ={}
            for j in range(1,ws.max_column+1):  
                contentJson[ws.cell(index,j).value]=ws.cell(i,j).value
            content.append(contentJson)
        jsonstr=json.dumps(content)

        wbnew = Workbook() 
        sheet = wbnew.active
        listHead=[]
        data= json.loads(jsonstr)
        for c,i in enumerate(data[0].keys()):
            sheet.cell(row=1,column=c+1,value=i)
            listHead.append(i)
        for r,i in enumerate(data):
            row=r+2
            for c,d in enumerate(listHead):
                sheet.cell(row=row,column=c+1,value=i.get(d,""))
        returnValue=os.path.exists(SendEmailExcelUrl)
        if returnValue==True:
            os.remove(SendEmailExcelUrl)
        wbnew.save(SendEmailExcelUrl)

  該內容只是個人記錄。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM