用oracle傳送電子郵件

space6212發表於2019-05-19
oracle內部提供傳送郵件的包,用它能給我們對資料庫的監控帶來很大用處。

create or replace procedure souchang_Send_Email(
p_txt varchar2,
p_sub Varchar2,
p_SendorAddress Varchar2,
p_ReceiverAddress varchar2,
p_EmailServer varchar2,
p_Port Number Default 25,
p_need_smtp Int Default 0,
p_user Varchar2 Default Null,
p_pass Varchar2 Default Null
)
IS
/*
作用:用oracle傳送郵件,支援多收件人。
作者:suk
引數說明:
p_txt :郵件正文
p_sub: 郵件標題
p_SendorAddress : 傳送人郵件地址
p_ReceiverAddress : 接收地址,可以同時傳送到多個地址上,地址之間用","或者";"隔開
p_EmailServer : 郵件伺服器地址,可以是域名或者IP
p_Port :郵件伺服器埠
p_need_smtp:是否需要smtp認證,0表示不需要,1表示需要
p_user:smtp驗證需要的使用者名稱
p_pass:smtp驗證需要的密碼
*/

l_addr Varchar2(200) :='';
l_len Int;
l_ReceiverAddress Varchar2(4000);

--真正傳送郵件的過程
procedure p_Email(p_txt varchar2,
p_sub Varchar2,
p_SendorAddress Varchar2,
p_ReceiverAddress varchar2,
p_EmailServer varchar2,
p_Port Number,
p_user Varchar2,
p_pass Varchar2
)
Is
l_conn UTL_SMTP.CONNECTION;--定義連線
l_crlf VARCHAR2( 2 ):= CHR( 13 ) || CHR( 10 );
l_mesg VARCHAR2( 4000 );

Begin
/*初始化郵件伺服器資訊,連線郵件伺服器*/
l_conn:= utl_smtp.open_connection( p_EmailServer, p_Port );
utl_smtp.helo( l_conn, p_EmailServer );

/* smtp伺服器登入校驗 */
If p_need_smtp=1 Then
utl_smtp.command(l_conn, 'AUTH LOGIN','');
utl_smtp.command(l_conn, utl_encode.base64_encode(utl_raw.cast_to_raw(p_user)), '');
utl_smtp.command(l_conn, utl_raw.cast_to_varchar2(utl_encode.base64_encode(utl_raw.cast_to_raw(p_pass))), '');
End If;

/*設定傳送地址和接收地址*/
utl_smtp.mail( l_conn, p_SendorAddress);
utl_smtp.rcpt( l_conn, p_ReceiverAddress );

/*設定郵件頭*/
l_mesg:=
'Content-Type: text/plain; Charset=GB2312' || l_crlf ||
'Date:' || TO_CHAR( SYSDATE, 'yyyy-mm-dd hh24:mi:ss' ) || l_crlf ||
'From:' || p_SendorAddress || l_crlf ||
'Subject: '||p_sub || l_crlf ||
'To: '|| p_ReceiverAddress || l_crlf ||
'Content-Type: text/plain; Charset=GB2312' || l_crlf ||
'' || l_crlf || p_txt || l_crlf ;

/*傳送郵件*/
utl_smtp.data( l_conn, l_mesg );

/*關閉與郵件伺服器的連線*/
utl_smtp.quit( l_conn );

/*異常處理*/
Exception
When Others Then
dbms_output.put_line(Sqlcode||':'||Sqlerrm);
--Raise;

End;


Begin
/*處理接收郵件地址列表,包括去空格、將;轉換為,等*/
l_ReceiverAddress:=trim(rtrim(replace(Replace(p_ReceiverAddress,';',','),' ',''),','));
l_len:=length(l_ReceiverAddress);

/*處理郵件地址,根據逗號分割郵件*/
For i In 1..l_len Loop
If substr(l_ReceiverAddress,i,1)<>',' Then
l_addr:=l_addr||substr(l_ReceiverAddress,i,1);
Else
--呼叫郵件傳送過程
p_Email(p_txt,p_sub,p_SendorAddress,l_addr,p_EmailServer,p_Port,p_user,p_pass);
l_addr:='';
End If;
If i=l_len Then
--呼叫郵件傳送過程
p_Email(p_txt,p_sub,p_SendorAddress,l_addr,p_EmailServer,p_Port,p_user,p_pass);
End If;
End Loop;

END;

執行:

SQL> exec souchang_send_email('sssss','ttttt','space6212@gmail.com','space6212@163.com','218.249.xx.xxx',25);

PL/SQL procedure successfully completed

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/231499/viewspace-63718/,如需轉載,請註明出處,否則將追究法律責任。

相關文章