01.Blogs :
mauriciogonzatto  
.NET, C#, Oracle, Web, tecnologia em geral e diversidades.

Enviar e-mail PL/SQL

Tenho uns cd's com uma coleçãozinha particular de material de diversas coisas, como há um ano atráz eu era programador PL/SQL, ainda sei programar, mas não com tanta confiança como antigamente, preciso relembrar alguns comandos, funções, sintaxe aquelas coisas que acontecem quando vc fica algum tempo sem mecher com a linguagem. Então, achei um código para enviar e-mail em PL/SQL, caso alguém queira matar a curiosidade, é lógico que com C# é beeeeeeem mais simples, mas é aquele negócio: "A ocasião faz o ladrão!"

CREATE OR REPLACE PROCEDURE PR_SENDMAIL (
       from_name     varchar2                    :='seu e-mail'
      ,to_name       varchar2                    :='e-mail'
      ,to_cc         varchar2                    :='cc'
      ,to_cco        varchar2                    :='cco'
      ,subject       varchar2                    :='Mensagem Oracle'
      ,message       varchar2                    :='Mensagem do Servidor Oracle'
      ,max_size      number   default 9999999999
      ,filename1  in varchar2                    :='/u41/spool/email/enviados/P183507.txt'
      ,filename2  in varchar2                    :='/u41/spool/email/enviados/P182303.txt'
      ,filename3  in varchar2                    :='/u41/spool/email/enviados/P182552.txt'
      ,debug         number   default 0 )

is

  v_smtp_server                          varchar2(30)                              := 'apisulweb'; -- Configuração para a CWI = 'mali.cwisl';
  v_smtp_server_port                     number                                    :=  25;
  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
   -- Carregando os arquivos dentro do ARRAY
   -- ---------------------------------------
   file_array(1) := filename1;
   file_array(2) := filename2;
   file_array(3) := filename3;

   -- Abrindo Conexão SMTP e HTTP
   -- ----------------------------
   conn  := utl_smtp.open_connection( v_smtp_server, v_smtp_server_port );

   -- Comunicando SMTP
   -- ------------------

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

   If to_cc is not null Then
      utl_smtp.rcpt( conn, to_cc );
   End If;
   
   If to_cco is not null Then
      utl_smtp.rcpt( conn, nvl(to_cco,0) );
   End If;

   utl_smtp.open_data ( conn );

   -- Criando Cabeça do E-mail
   -- -----------------------------------
   mesg:= 'Date: '    || TO_CHAR( SYSDATE, 'dd Mon yy hh24:mi:ss' )                     || crlf ||
          'From: '    || from_name                                                      || crlf ||
          'Subject: ' || subject                                                        || crlf ||
          'To: '      || to_name                                                        || crlf ||
          'Cc: '      || nvl(to_cc,'')                                                        || crlf ||
          'Cco: '      || nvl(to_cco,'')                                                        || 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:              text/plain; 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 );

   -- Anexando Arquivos
   -- ------------------
   for i in  1..3 loop

       -- Sair se ultrapassar o tamanho de mensagem
       -- -----------------------------------------
       exit when mesg_length_exceeded;

       if file_array(i) is not null then

          begin

             -- Localiza a '/' ou '\' no caminho
             -- ---------------------------------
             v_slash_pos := instr(file_array(i), '/', -1 );

             if v_slash_pos = 0 then
                v_slash_pos := instr(file_array(i), '\', -1 ); -- Valor Retornado = 3

             end if;

             -- Separa o arquivo do diretório
             -- ------------------------------
             v_directory_name := substr(file_array(i), 1, v_slash_pos - 1);
             v_file_name      := substr(file_array(i), v_slash_pos + 1 );

             -- Abrir Arquivo
             -- --------------
             v_file_handle := utl_file.fopen('DIR_AVERBNET',v_file_name,'r');

             -- Gera a linha MIME boundary
             -- --------------------------
             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 );

             -- Anexa o conteúdo do arquivo ao corpo da mensagem
             -- ------------------------------------------------

             loop

                 utl_file.get_line(v_file_handle, v_line);

                 if mesg_len + length(v_line) > max_size then

                    mesg := '*** truncado ***' || 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('Erro anexando arquivo ! '|| file_array(i));
                 end if;

             -- Todas EXCEPTIONS ignoradas
             when others then null;

          end;

          mesg := crlf;

          utl_smtp.write_data ( conn, mesg );

          -- Fecha Arquivo
          -- --------------
          utl_file.fclose(v_file_handle);

        end if;

   end loop;

   -- Fechando a Cabeça do E-mail
   -- ----------------------------
   mesg := crlf || '--DMW.Boundary.605592468--' || crlf;
   utl_smtp.write_data ( conn, mesg );

   -- Fechando conexão SMTP
   -- -----------------------
   utl_smtp.close_data( conn );
   utl_smtp.quit( conn );

end;

 

foda neh!?!?

=]

[]'s

posted on Wednesday, December 07, 2005 4:24 AM by mauriciogonzatto


 
03.UPDATE CALENDAR :
<December 2005>
SunMonTueWedThuFriSat
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567

05.MY LINKS :

07.Subscriptions :

Subscriptions


© Copyright 2005 Microsoft Corporation. All Rights Reserved.
Terms of Use | Privacy Statement | Code of Conduct | Hosted by MaximumASP for Microsoft
WHO-BAR