How can I send email from Oracle?

How can I send email from Oracle?

Question:
How can I send email from Oracle?

Answer:
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# ora_emailer.pl - 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/sendmail.cf 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/ora_emailer.pl *)##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.
Share the Post:
XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes

ransomware cyber attack

Why Is Ransomware Such a Major Threat?

One of the most significant cyber threats faced by modern organizations is a ransomware attack. Ransomware attacks have grown in both sophistication and frequency over the past few years, forcing

data dictionary

Tools You Need to Make a Data Dictionary

Data dictionaries are crucial for organizations of all sizes that deal with large amounts of data. they are centralized repositories of all the data in organizations, including metadata such as