Thursday, August 16, 2018

How to use the SMTP package to send email in Oracle Database

Using UTL_SMTP


DECLARE
  c UTL_SMTP.CONNECTION;

  PROCEDURE send_header(name IN VARCHAR2, header IN VARCHAR2) AS
  BEGIN
    UTL_SMTP.WRITE_DATA(c, name || ': ' || header || UTL_TCP.CRLF);
  END;

BEGIN
  c := UTL_SMTP.OPEN_CONNECTION('172.30.160.53');
  UTL_SMTP.HELO(c, 'google.com');
  UTL_SMTP.MAIL(c, 'Finch.Chen@Linde-lienhwa.com.tw'); --sender
  UTL_SMTP.RCPT(c, 'Finch.Chen@Linde-lienhwa.com.tw'); --recipient
  UTL_SMTP.OPEN_DATA(c);
  send_header('From',    '"Sender" <Finch.Chen@Linde-lienhwa.com.tw>');
  send_header('To',      '"Recipient" <Finch.Chen@Linde-lienhwa.com.tw>');
  send_header('Subject', 'Hello');
  UTL_SMTP.WRITE_DATA(c, UTL_TCP.CRLF || 'Hello, world!');
  UTL_SMTP.CLOSE_DATA(c);
  UTL_SMTP.QUIT(c);
EXCEPTION
  WHEN utl_smtp.transient_error OR utl_smtp.permanent_error THEN
    BEGIN
      UTL_SMTP.QUIT(c);
    EXCEPTION
      WHEN UTL_SMTP.TRANSIENT_ERROR OR UTL_SMTP.PERMANENT_ERROR THEN
        NULL; -- When the SMTP server is down or unavailable, we don't have
              -- a connection to the server. The QUIT call will raise an
              -- exception that we can ignore.
    END;
    raise_application_error(-20000,
      'Failed to send mail due to the following error: ' || sqlerrm);
END;

No comments:

Post a Comment