Envio de email com anexo (excel .SYLK) não funciona mais.

Dúvidas, dicas e truques de PL/SQL. Aqui também vão assuntos relacionados a pacotes, triggers, funções, Java-Stored Procedures, etc
Responder
hashashyyn
Rank: Estagiário Júnior
Rank: Estagiário Júnior
Mensagens: 1
Registrado em: Sex, 30 Set 2011 5:44 pm
Localização: São Paulo SP

Pessoal,

Preciso de ajuda para encontrar uma solução para um incidente. Tenho uma procedure que em resumo gera um arquivo excel no formato SYLK e o salva em um diretório do banco de dados, confere se o arquivo tem dados, depois disso gera um email html e dispara o email para os usuários com o arquivo em anexo.
Esse processo funcionava corretamente, porém, trocamos a instância de banco de dados para esse sistema e após isso o usuário recebe o email sem anexo algum, mesmo o anexo estando no diretório correto. Ambas as instâncias estão na mesma versão do Oracle, 10g.
Abaixo segue o código para enviar o email, não sei mais o que analisar, já verifiquei permissões de acesso ao diretório pelos usuários de banco, o sendmailer, a rotina foi verificada algumas vezes e no ambiente de desenvolvimento funciona.
Se alguém souber de algo que possa ajudar, agradeço.

Selecionar tudo

FUNCTION FN_ENVIA_EMAIL ( p_to      in  VARCHAR2
                           , p_subject in  VARCHAR2
                           , p_body    in out  VARCHAR2
                           , p_formato in  VARCHAR2 default 'TEXT'
                           , p_arq1    in  VARCHAR2 default NULL ) RETURN BOOLEAN IS

      conn utl_smtp.connection;
      v_from       varchar2(100)  := 'cadcorp_cpm@abril.com.br';
      v_retorno    boolean := true;
   BEGIN

      v_retorno := True;
      if p_formato = 'TEXT' then
         if p_arq1 is null then
           mail( sender     => v_from
               , recipients => p_to
               , subject    => p_subject
               , message    => p_body );
         else
           -- Envia e-mail com anexo
           mail_files( p_to        => p_to
                     , p_subject   => p_subject
                     , p_body      => p_body
                     , p_formato   => p_formato
                     , p_arq1      => p_arq1 );
         end if;
      elsif p_formato = 'HTML' then
         p_body := replace(p_body,'á',chr(38)||'aacute;');
         p_body := replace(p_body,'â',chr(38)||'acirc;' );
         p_body := replace(p_body,'à',chr(38)||'agrave;');
         p_body := replace(p_body,'ã',chr(38)||'atilde;');
         p_body := replace(p_body,'ç',chr(38)||'ccedil;');
         p_body := replace(p_body,'é',chr(38)||'eacute;');
         p_body := replace(p_body,'ê',chr(38)||'ecirc;' );
         p_body := replace(p_body,'í',chr(38)||'iacute;');
         p_body := replace(p_body,'ó',chr(38)||'oacute;');
         p_body := replace(p_body,'ô',chr(38)||'ocirc;' );
         p_body := replace(p_body,'õ',chr(38)||'otilde;');
         p_body := replace(p_body,'ú',chr(38)||'uacute;');
         p_body := replace(p_body,'ü',chr(38)||'uuml;'  );
         p_body := replace(p_body,'Á',chr(38)||'Aacute;');
         p_body := replace(p_body,'Â',chr(38)||'Acirc;' );
         p_body := replace(p_body,'À',chr(38)||'Agrave;');
         p_body := replace(p_body,'Ã',chr(38)||'Atilde;');
         p_body := replace(p_body,'Ç',chr(38)||'Ccedil;');
         p_body := replace(p_body,'É',chr(38)||'Eacute;');
         p_body := replace(p_body,'Ê',chr(38)||'Ecirc;' );
         p_body := replace(p_body,'Í',chr(38)||'Iacute;');
         p_body := replace(p_body,'Ó',chr(38)||'Oacute;');
         p_body := replace(p_body,'Ô',chr(38)||'Ocirc;' );
         p_body := replace(p_body,'Õ',chr(38)||'Otilde;');
         p_body := replace(p_body,'Ú',chr(38)||'Uacute;');
         p_body := replace(p_body,'Ü',chr(38)||'Uuml;'  );

         if p_arq1 is null then
           conn := begin_mail( sender     => v_from
                             , recipients => p_to
                             , subject    => p_subject
                             , mime_type  => 'text/html' );

           write_text( conn    => conn
                     , message => p_body );

           end_mail( conn => conn );
         else
           -- Envia e-mail com anexo
           mail_files( p_to        => p_to
                     , p_subject   => p_subject
                     , p_body      => p_body
                     , p_formato   => p_formato
                     , p_arq1      => p_arq1 );
         end if;
      end if;
      Return v_retorno;
   EXCEPTION
      when others then
           v_retorno := False;
           Return v_retorno;
   END FN_ENVIA_EMAIL;


create or replace procedure mail_files ( from_name varchar2
                                       , to_name   varchar2
                                       , subject   varchar2
                                       , type_msg  varchar2       default 'T'
                                       , message   varchar2
                                       , max_size  number         default 9999999999
                                       , filename1 varchar2       default null
                                       , filename2 varchar2       default null
                                       , filename3 varchar2       default null
                                       , debug number default 0 ) is

  --v_smtp_server      varchar2(100)  := '10.251.32.21';   -- Alterado de 'localhost' para '10.251.32.21'
  --v_smtp_server_port number         := 25;
  smtp_server        varchar2(1000) := 'exnea01.abril.com.br';
  smtp_server_port   number(4) := 25;
  v_type_msg         varchar2(100);
  v_directory_name   varchar2(100);
  v_file_name        varchar2(100);
  v_line             varchar2(1000);
  crlf               varchar2(2)    := chr(13) || chr(10);
  mesg               varchar2(32767);
  conn               UTL_SMTP.CONNECTION;
  type varchar2_table is table of varchar2(200) index by binary_integer;
  file_array         varchar2_table;
  i                  binary_integer;
  v_file_handle      utl_file.file_type;
  v_slash_pos        number;
  mesg_len           number;
  mesg_too_long      exception;
  invalid_path       exception;
  mesg_length_exceeded boolean      := false;

begin

   file_array(1) := filename1;
   file_array(2) := filename2;
   file_array(3) := filename3;

   if type_msg = 'T' then
      v_type_msg := 'text/plain';
   elsif type_msg = 'H' then
      v_type_msg := 'text/html';
   end if;

   conn:= utl_smtp.open_connection( smtp_server, smtp_server_port );

   utl_smtp.helo( conn, smtp_server );
   utl_smtp.mail( conn, from_name );
   utl_smtp.rcpt( conn, to_name );

   utl_smtp.open_data ( conn );

   mesg := 'Date: ' || TO_CHAR( SYSDATE, 'dd Mon yy hh24:mi:ss' ) || crlf ||
           'From: ' || from_name || crlf ||
           'Subject: ' || subject || crlf ||
           'To: ' || to_name || crlf ||
           'Mime-Version: 1.0' || crlf ||
           'Content-Type: multipart/mixed; boundary="DMW.Boundary.605592468"' || crlf ||
           '' || crlf ||
           'This is a Mime message, which your current mail reader may not' || crlf ||
           'understand. Parts of the message will appear as text. If the remainder' || crlf ||
           'appears as random characters in the message body, instead of as' || crlf ||
           'attachments, then you''ll have to extract these parts and decode them' || crlf ||
           'manually.' || crlf ||
           '' || crlf ||
           '--DMW.Boundary.605592468' || crlf ||
           'Content-Type: ' || v_type_msg || '; name="message.txt"; charset=US-ASCII' || crlf ||
           'Content-Disposition: inline; filename="message.txt"' || crlf ||
           'Content-Transfer-Encoding: 7bit' || crlf ||
           '' || crlf ||
           message || crlf ;

   mesg_len := length(mesg);

   if mesg_len > max_size then
      mesg_length_exceeded := true;
   end if;

   utl_smtp.write_data ( conn, mesg );

   for i in  1..3 loop
       exit when mesg_length_exceeded;
       if file_array(i) is not null then
          begin
             v_slash_pos := instr(file_array(i), '/', -1 );
             if v_slash_pos = 0 then
                v_slash_pos := instr(file_array(i), '\', -1 );
             end if;

             v_directory_name := substr(file_array(i), 1, v_slash_pos - 1 );
             v_file_name      := substr(file_array(i), v_slash_pos + 1 );

             v_file_handle := utl_file.fopen(v_directory_name, v_file_name, 'r' );

             mesg := crlf || '--DMW.Boundary.605592468' || crlf ||
                     'Content-Type: application/octet-stream; name="' || v_file_name || '"' || crlf ||
                     'Content-Disposition: attachment; filename="' || v_file_name || '"' || crlf ||
                     'Content-Transfer-Encoding: 7bit' || crlf || crlf ;

             mesg_len := mesg_len + length(mesg);
             utl_smtp.write_data ( conn, mesg );
             loop
                 utl_file.get_line(v_file_handle, v_line);
                 if mesg_len + length(v_line) > max_size then
                    mesg := '*** truncated ***' || crlf;
                    utl_smtp.write_data ( conn, mesg );
                    mesg_length_exceeded := true;

                    raise mesg_too_long;
                 end if;

                 mesg := v_line || crlf;
                 utl_smtp.write_data ( conn, mesg );
                 mesg_len := mesg_len + length(mesg);
             end loop;

          exception

             when utl_file.invalid_path then
                 if debug > 0 then
                    dbms_output.put_line('Error in opening attachment '|| file_array(i) );
                 end if;

             when others then
                 null;
          end;
          mesg := crlf;
          utl_smtp.write_data ( conn, mesg );
          utl_file.fclose(v_file_handle);
        end if;
   end loop;
   mesg := crlf || '--DMW.Boundary.605592468--' || crlf;
   utl_smtp.write_data ( conn, mesg );
   utl_smtp.close_data( conn );
   utl_smtp.quit( conn );
end;
Avatar do usuário
stcoutinho
Moderador
Moderador
Mensagens: 850
Registrado em: Qua, 11 Mai 2011 5:15 pm
Localização: são Paulo - SP

hashashyyn,

Os bancos são exatamente iguais? Ou seja, uma instância seria CLONE da outra?
O conjunto de caracteres da instância, a versão do sistema operacional, etc ... seria tudo exatamente igual?
O que poderia haver de diferença mínima entre estes ambientes?

Abraços,

Sergio Coutinho
Avatar do usuário
stcoutinho
Moderador
Moderador
Mensagens: 850
Registrado em: Qua, 11 Mai 2011 5:15 pm
Localização: são Paulo - SP

Complementando informações,

No metalink, existe uma série de notas que você poderia usar para avaliar seu problema:

Frequently Asked Questions:
=====================

Note 730746.1 FAQ and Known Issues While Using UTL_SMTP and UTL_MAIL

Note 413099.1 Does UTL_SMTP or UTL_MAIL Support TLS Connection?

Note 369777.1 FAQ about UTL_TCP, UTL_SMTP and UTL_MAIL

How To:
=====

Selecionar tudo

Note 74269.1   How to Test an SMTP Mail Gateway From a Command Line 

Note 106513.1 Basics on How to use UTL_SMTP 

Note 161407.1 How To Send E-mail Containing 8-bit Characters Using UTL_SMTP 

Note 180017.1 How To Specifiy a 'Reply-To' Using UTL_SMTP 

Note 209364.1 How to Send Pager Messages to Mobile Phones using the UTL_SMTP package 

Note 270155.1 How to Programmatic With PL/SQL Send an Email Which Will Allow a Hyperlink to be Created?  

Note 302943.1 Sending Mail Using UTL_SMTP Special Chars And Attach File Problem 

Note 357385.1 How To Send Attachments Of Size Greater Than 32 KB Using UTL_SMTP Package

Infelizmente, para acessar as notas acima, é necessário uma conta no Metalink.

Att.

Sergio
Responder
  • Informação
  • Quem está online

    Usuários navegando neste fórum: Nenhum usuário registrado e 11 visitantes