Problem with encode / decode python

0

I have 2 functions, the first prepares the html and writes to a .txt file so that the second function opens this file and manages an email through outlook. In the body of the message, the content of this html will be placed with the correct formatting. Everything goes perfectly, the .txt comes with the html without any error, but when the outlook is opening, it is closed and the Error / Exception is generated below:

  

'ascii' codec can not encode character u '\ xe7' in position 529: ordinal not in range (128)

I know that this "\ xe7" is 'ç', but I can not solve it, I tried to define it by .decode ("utf-8") and encode ("utf-8"), in the variable 'email_html_lement' but the codec error persists. Follow the code of the 2 functions to see if I did something wrong:

  

Function 1:

import sys
import codecs
import os.path

def gerar_html_do_email(self):
    texto_solic = u'Solicitação Grupo '
    with codecs.open('html.txt', 'w+', encoding='utf8') as email_html:
        try:
            for k, v in self.dicionario.iteritems():
                email_html.write('<h1>'+k+'</h1>'+'\n')
                for v1 in v:
                    if (v1 in u'Consulte o documento de orientação.') or (v1 in u'Confira o documento de orientação.'):
                        for x, z in self.tit_nome_pdf.iteritems():
                            if x in k:
                                email_html.write('<a href='+'%s/%s'%(self.hiperlink,z+'>')+'Mais detalhes'+'</a>'+'\n')
                    else:
                        email_html.write('<p>'+v1+'</p>'+'\n')
                email_html.write('<p><i>'+texto_solic+'</i></p>'+'\n')
            email_html.close()
        except Exception as erro:
            self.log.write('gerar_html_para_o_email: \n%s\n'%erro)
  

Function 2:

def gerar_email(self):
    import win32com.client as com
    try:
        outlook       = com.Dispatch("Outlook.Application")
        mail          = outlook.CreateItem(0)
        mail.To       = u"Lista Liberação de Versões Sistema"
        mail.CC       = u"Lista GCO"
        mail.Subject  = u"Atualização Semanal Sistema Acrool"
        with codecs.open('html.txt', 'r+', encoding='utf8') as email_html_leitura:
            mail.HTMLBody = """
                            <html>
                                <head></head>
                                <body>
                                    <style type=text/css>
                                        h1{
                                            text-align: center;
                                            font-family: "Arial";
                                            font-size: 1.1em;
                                            font-weight: bold;
                                        }
                                        p{
                                            text-align: justify;
                                            font-family: "Arial";
                                            font-size: 1.1em;
                                        }
                                        a{
                                            font-family: "Arial";
                                            font-size: 1.1em;
                                        }
                                    </style>
                                    %s
                                </body>
                            </html>
                            """%(email_html_leitura.read().decode("utf-8"))
        email_html_leitura.close()
        mail.BodyFormat = 2
        mail.Display(True)
    except Exception as erro:
        self.log.write('gerar_email: \n%s\n'%erro)

If someone can help me, thank you, every week I have to do a dull task of creating this email and formatting in a pattern and everything manually, as the data is changed every week and most of the time, there are many. With him, I'm going to win almost a whole morning. Thank you.

    
asked by anonymous 28.11.2017 / 03:24

1 answer

0

I think the problem is in the source file not having unicode encoding.

You can put this excerpt at the very beginning of your file:

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

Another solution is to use python3

#Edit: Added solution that solved the problem

reload(sys)
sys.setdefaultencoding('utf8')
    
28.11.2017 / 12:54