標籤:
1、建立發送郵件的預存程序
CREATE OR REPLACE PROCEDURE send_mail(p_recipient VARCHAR2, -- 郵件接收人
p_subject VARCHAR2, -- 郵件標題
p_message VARCHAR2 -- 郵件內文
) IS
--下面四個變數請根據實際郵件伺服器進行賦值
v_mailhost VARCHAR2(30) := ‘123.125.50.135‘; --SMTP伺服器位址
v_user VARCHAR2(30) := ‘******‘; --登入SMTP伺服器的使用者名稱
v_pass VARCHAR2(20) := ‘******‘; --登入SMTP伺服器的密碼
v_sender VARCHAR2(50) := ‘******@163.com‘; --寄件者郵箱,一般與 ps_user 對應
v_conn UTL_SMTP.connection; --到郵件伺服器的串連
v_msg varchar2(4000); --郵件內容
BEGIN
v_conn := UTL_SMTP.open_connection(v_mailhost, 25);
UTL_SMTP.ehlo(v_conn, v_mailhost); --是用 ehlo() 而不是 helo() 函數
--否則會報:ORA-29279: SMTP 永久性錯誤: 503 5.5.2 Send hello first.
UTL_SMTP.command(v_conn, ‘AUTH LOGIN‘); -- smtp伺服器登入校正
UTL_SMTP.command(v_conn,
UTL_RAW.cast_to_varchar2(UTL_ENCODE.base64_encode(UTL_RAW.cast_to_raw(v_user))));
UTL_SMTP.command(v_conn,
UTL_RAW.cast_to_varchar2(UTL_ENCODE.base64_encode(UTL_RAW.cast_to_raw(v_pass))));
UTL_SMTP.mail(v_conn, ‘<‘ || v_sender || ‘>‘); --設定寄件者
UTL_SMTP.rcpt(v_conn, ‘<‘ || p_recipient || ‘>‘); --設定收件者
-- 建立要發送的郵件內容 注意前序資訊和郵件內文之間要空一行
v_msg := ‘Date:‘ || TO_CHAR(SYSDATE, ‘yyyy mm dd hh24:mi:ss‘) ||
UTL_TCP.CRLF || ‘From: ‘ || v_sender || ‘‘ || UTL_TCP.CRLF ||
‘To: ‘ || p_recipient || ‘‘ || UTL_TCP.CRLF || ‘Subject: ‘ ||
p_subject || UTL_TCP.CRLF || UTL_TCP.CRLF -- 這前面是前序資訊
|| p_message; -- 這個是郵件內文
UTL_SMTP.open_data(v_conn); --開啟流
UTL_SMTP.write_raw_data(v_conn, UTL_RAW.cast_to_raw(v_msg)); --這樣寫標題和內容都能用中文
UTL_SMTP.close_data(v_conn); --關閉流
UTL_SMTP.quit(v_conn); --關閉串連
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.put_line(DBMS_UTILITY.format_error_stack);
DBMS_OUTPUT.put_line(DBMS_UTILITY.format_call_stack);
END send_mail;
2、建立完預存程序需要配置額外的許可權(建立的步驟不能錯)
begin
dbms_network_acl_admin.create_acl (
acl => ‘sendmail.xml‘, ---建立的存取控制清單名字
description => ‘Normal Access‘,
principal => ‘CONNECT‘,
is_grant => TRUE,
privilege => ‘connect‘,
start_date => null,
end_date => null
);
end;
----------------------------------------------------------------
begin
dbms_network_acl_admin.add_privilege(acl => ‘sendmail.xml‘,
principal => ‘ABS_20160104‘,
is_grant => TRUE,
privilege => ‘connect‘,
start_date => null,
end_date => null);
end;
----------------------------------------------------------------
begin
dbms_network_acl_admin.assign_acl (
acl => ‘utlpkg.xml‘,
host => ‘123.125.50.135‘, --可訪問伺服器的地址
lower_port => 25, ---最低連接埠
upper_port => 25); --最高連接埠
end;
----------------------------------------------------------------
--刪除許可權檔案
BEGIN
DBMS_NETWORK_ACL_ADMIN.drop_acl(acl => ‘sendmail.xml‘);
COMMIT;
END;
--查詢全限檔案
SELECT * FROM resource_view WHERE any_path like ‘/sys/acls/%.xml‘;
--查詢檔案網路許可權
SELECT host, lower_port, upper_port, acl FROM dba_network_acls;
--查詢使用者的網路許可權
SELECT acl,
principal,
privilege,
is_grant,
TO_CHAR(start_date, ‘DD-MON-YYYY‘) AS start_date,
TO_CHAR(end_date, ‘DD-MON-YYYY‘) AS end_date
FROM dba_network_acl_privileges;
現在可以調用預存程序發送郵件。
oracle發送郵件