Oracle的包utl_smtp提供了从数据库中直接发送电子邮件的功能,这里介绍一下其使用方法
网上找到的例子以及Oracle文档中的例子都没有提到authorized的问题,我的测试中使用的是
163的免费信箱,发送时老是报错:
ORA-20000: Failed to send mail due to the following error:
ORA-29279: SMTP 永久性错误: 553 You are not authorized to send mail as , authentication is required
后来在metalink上找到解决方法:要在程序中增加登录smtp服务器的过程!
[@more@]
测试环境: RedHat AS 3.0 Oracle 9.2.0.6
SMTP服务器: smtp.163.com(ip地址202.108.44.205)
下面是存储过程的源代码,注意数据库服务器必须要能访问smtp.163.com
CREATE OR REPLACE PROCEDURE send_mail (
p_recipient IN VARCHAR2,
p_message IN VARCHAR2,
p_subject IN VARCHAR2 default 'Oracle Perf Report '||to_char(sysdate,'yyyy-mm-dd hh24:mi:ss'),
p_sender IN VARCHAR2 default 'demo@163.com')
IS
v_mailhost varchar2(30) := '202.108.44.205'; -- SMTP服务器地址
mail_conn utl_smtp.connection;
msg varchar2(4000);
p_user varchar2(30) := 'demo'; -- 登录SMTP服务器的用户名
p_pass varchar2(30) := 'demo'; -- 登录SMTP服务器的密码
BEGIN
/* 创建要发送的邮件内容 注意报头信息和邮件正文之间要空一行 */
msg := 'Date:' ||to_char(sysdate,'dd mon yy hh24:mi:ss') || utl_tcp.CRLF ||
'From: ' || p_sender || '' ||utl_tcp.CRLF ||
'To: '|| p_recipient || '' ||utl_tcp.CRLF||
'Subject: '||p_subject || utl_tcp.CRLF ||utl_tcp.CRLF||
p_message;
-- dbms_output.put_line(msg);
mail_conn := utl_smtp.open_connection(v_mailhost,25);
utl_smtp.helo(mail_conn,v_mailhost);
/* smtp服务器登录校验 */
utl_smtp.command(mail_conn, 'AUTH LOGIN');
utl_smtp.command(mail_conn, utl_raw.cast_to_varchar2(utl_encode.base64_encode(utl_raw.cast_to_raw(p_user))));
utl_smtp.command(mail_conn, utl_raw.cast_to_varchar2(utl_encode.base64_encode(utl_raw.cast_to_raw(p_pass))));
utl_smtp.mail(mail_conn,p_sender);
utl_smtp.rcpt(mail_conn,p_recipient);
/* 发送数据 */
utl_smtp.data(mail_conn, msg);
utl_smtp.quit(mail_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;
测试这个存储过程:
SQL> exec send_mail('demo2@163.com','This is a oracle send mail demo!!!');
PL/SQL procedure successfully completed
参考资料:
1、《Oracle9i Supplied PL/SQL Packages and Types Reference》100 UTL_SMTP
2、网友mugen的《oracle 发邮件的程序》:http://blog.itpub.net/post/76/9913
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/3898/viewspace-786450/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/3898/viewspace-786450/