How can I send email from Oracle?

How can I send email from Oracle?

How can I send email from Oracle?

A recurring question on Oracle developer listsis how to send email from “within” Oracle. One might want a certain event in the database to trigger an email message to one of the DBAs.Or, one might have a computerized help desk in which users submitproblems via a World Wide Web form; based on the form contents, one might send an automatic response and want it to appear to be an an email from support staff.

There is more than one way to do this, of course. Oracle Mail canbe used, but it’s an added-cost option. On the other hand, one couldpass the message to sendmail via a dbms_pipe to a Pro*C daemon writtento execute general OS commands, but such a daemon is a security risk(not to mention the small limit on information that can be passedvia a dbms_pipe that uses a 4K buffer).

Both of these options are more complicated than need be if the messages don’t have to be sent as soon as received. Rather,one can simply use the utl_file package to write messages to anOS file, then launch a cron script every 10 minutes or so tosend the messages. The only challenge left is figuring out how topass all the needed information to sendmail. But that turns outto be easy:

  1. Use the file name to pass the “from” address.
  2. Add a sequence number to the file name to make the file names unique.
  3. Use a -t switch to sendmail to tell it to get the other information straight from the file.

#!/usr/local/bin/perl# - script to send e-mail messages created# with Oracle's PL/SQL (using the utl_file package to do UNIX I/O).# The -t flag to sendmail tells it to get To:, etc. from# the message itself. The -f flag forces the From: (so the# executor of the script needs to be designated a Trusted# user in the /etc/ file. The script assumes that the # file name is of the form: from_address.sequence_number (thus# passing all needed info via the file but also preventing# message overwriting).#   It is, of course, up to the pl/sql package generating# the message file to do any security checking deemed necessary# wrt the From: address, etc.# # #usage: evoke with cron, using say:#  #   5,15,25,35,45,55 * * * * (cd /orafiles/email; /usr/sbin/ *)##NOTE: Put a file name dummy in the dir so the shell doesn't complain#      about * not expanding to anything (or, change the way#      the script gets the file names).## change history: creation: 06-Dec-96 [email protected] $curtime=time;$symlink_magic_nr=41471;#  ^--system dependent for (@ARGV) {#first, strip out bad characters  tr/;\///d;  s/..//g;  $filename=$_;  if ($filename ne "dummy") {    s/(.+).[0-9]+$/1/;    $from = $_;    ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,      $atime,$mtime,$ctime,$blksize,$blocks)=lstat($filename);    $diff=$curtime-$mtime;    if (($diff>240) and ($mode!=$symlink_magic_nr)) {      system("/usr/lib/sendmail -f $from -t 

The message itself can be generated via a pl/sql procedure. This is also a good opportunity to introduce packages.

create package ora_emailer asprocedure send_email(from_i in varchar2, pw_i in varchar2,     to_i in varchar2, msg_i in varchar2,      subject_i in varchar2:='Re:', cc_i in varchar2:='',       bcc_i in varchar2 default '');end;/show errors;create package body ora_emailer as--NOTE: Since write_email is not declared in package specification,--      it is a private procedure that can be called only from --      other procedures in the package body of ora_emailer, i.e.--      from send_email. procedure write_email(from_i in varchar2,to_i in varchar2,msg_i in varchar2,     subject_i in varchar2,cc_i in varchar2,bcc_i in varchar2) is fnum number; fname varchar2(200); f utl_file.file_type; m varchar2(32000);begin  select fn_email_seq.nextval into fnum from dual;  fname:=from_i||'.'||to_char(fnum);  f:=utl_file.fopen('/orafiles/email',fname,'W');  utl_file.putf(f,'To: %s
',to_i);  if cc_i is not null then    utl_file.putf(f,'Cc: %s
',cc_i);  end if;  if bcc_i is not null then    utl_file.putf(f,'Bcc: %s
',bcc_i);  end if;  utl_file.putf(f,'Subject: %s

',subject_i);  m:=msg_i;  while length(m)>999 loop    utl_file.put(f,substr(m,1,1000));    m:=substr(m,1001);  end loop;  if length(m)>0 then    utl_file.put(f,m);  end if;  utl_file.fclose(f);  dbms_output.put_line('Message in queue');exceptionwhen others then   utl_file.fclose(f);  dbms_output.put_line('Unexpected error, debugging info: '                         ||sqlcode||': '||sqlerrm);end;procedure send_email(from_i in varchar2, pw_i in varchar2,     to_i in varchar2, msg_i in varchar2,      subject_i in varchar2:='Re:', cc_i in varchar2:='',       bcc_i in varchar2 default '') is ok number;beginselect count(address) into ok from email_addresses   where address=from_i and passwd=pw_i;if ok=1 then  procedure write_email(from_i,to_i,msg_i,subject_i,cc_i,bcc_i);else  dbms_output.put_line('Permission denied.');end if;end;end;/show errors;  

I'll have much more to say about PL/SQL in future answers; for now,note that:

  • PL/SQL inherits several nice features from Ada (packages, exception handling, overloading) that make the language a pleasure.
  • PL/SQL is integrated more seamlessly into Oracle than any other procedural language, so development and maintenance are less costly than with other alternatives such as C++.
  • The send_email procedure assumes addresses are stored in a table: email_addresses.
See also  Redefining Energy Management: Advanced Solutions for Modern Buildings

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist