SMTP bounce code

I'm not familiar with SMTP standards, but is there any SMTP mandated bounce/error code I can use in my application? I'm working on SMTP classification at the moment. Thanks.

SMTP does define message codes from server to client to indicate success/failure. However, I don't think the Java Mail API provides any methods to get these codes (outside of sessing debug to be on - which just dumps the to STDOUT).

Similar Messages

  • Get SMTP reply code

    Hi,
    I am using destination mail server to send emails. For example to send an email to [email protected] , I do an MX lookup on mailservers for hotmail.com and use that to send mail to user fred. The reason for this is that
    I get better email validation. For example - if user fred does not exist then, I know it straight away as I get error 550.
    From what I can see, Javamail does not provide functionality to retreive SMTP reply code. It will be good if a method is added to Messaging Exception class that returns the SMTP reply code that caused the exception.
    From what I understand, the only method to get SMTP reply code is to parse the exception message for an int.
    Is there any alternative to get the SMTP reply code that caused the exception?
    Regards,
    Anmol

         public static int getSmtpErrorCode (Exception ex){
              String exceptionString = ex.toString();
              StringTokenizer tokens = new StringTokenizer(exceptionString);
              int code = 0;
              boolean flag = false;
              while(tokens.hasMoreTokens()){
                   if (flag == true) {
                        break;
                   try {
                        flag = true;
                        code = Integer.parseInt(tokens.nextToken());
                   } catch (Exception e){
                        flag = false;
              return code;
         }

  • SMTP Error Code : 530 . For more information, see your SMTP server manual.

    Hello,
    I am Getting
    "SMTP Error Code : <530>. For more information, see your SMTP server manual" error, While configuring SMTP in Data Services 4.0 system. I have tried executing the SMTP_TO function on another DS machine which has 3.2 verion installed, but getting the same error.
    FYI,
    1) Able to telnet the Exchange server through Data service machine
    2) Maintained SMTP settings in Data services server manager
    3) using the same SMTP server host name in other SAP systems (ECC,BI,PI) etc and able to send mails.
    Regards
    Puneet

    Thanks for the reply Julian.
    There was a problem in SMTP relay rights on Exchange server. Able to send mails now. Thanks!
    Getting another problem wherein I am not able to send mails to multiple recipients i.e. If I specify 5 recipients in SMTP_TO function and execute the job then Every individual is getting E-Mail having there own ID in TO field, other Id's are not gettting displayed in TO field.
    I hve checked note "1276348 - smtp_to function - multiple recipients not displayed"
    Settings mentioned in the note have been done and job is getting executed without any error but the mails are not getting delivered.
    It would be great if anyone can suggest on how to proceed here.
    Thanks & Regards
    Puneet

  • Get SMTP response codes?

    Is there any standard way when using JavaMail to retrieve the SMTP response code from a failed send? Specifically, if a message fails to send I want to see if it was a 5xx 5.x.x permanent error (in which case I would not retry) or a 4xx 4.x.x temporary failure (in which case I would wait a bit then try again)?
    I know the SMTP response codes are available in the text of the MessagingException, but parsing that text seems a bit fragile since you're at the mercy of the formatting in that particular implementation.
    Thanks.

    I may be mistaken, but I believe the rules are that the numerical status code MUST be at the very beginning of the response, and everything after that numeric response is optional. So parsing shouldn't be a big deal. Snatch up the first three characters, and that ought to be everything you need.

  • How to extract the smtp response code

    Hi,
    I am trying to get the server response by SMTPTransport.getLastServerResponse(),
    and getting the response as "250 2.0.0 OK 1201842889 c39sm4983397anc.25", in case of success.
    This response would differ in case of failure.
    Could please guide me as how to extract the response code from the result.
    Thanks!!

    It's time to read the SMTP spec.
    Also, read the javadocs for the com.sun.mail.smtp
    package to see how to get an Exception even for
    success that includes the detailed response codes.
    The smtpsend.java demo program will show you how
    to interpret the exception.

  • Smtp bounced messages

    Hi all,
    i have R12 configure with Workflow mail with smtp server.
    1 . how can i make sure that all my messages are delived
    2. where do i check my bounced messages.
    3. do i need to have imap server configure to receive my bounced messages.
    fast responses are appreciated.
    thanks,
    Vamshi D

    Run the following diagnostic tests to validate Workflow configurations:
    Note: 471687.1 - Oracle Application Object Library Notification Preference Validation Setup Test
    https://metalink2.oracle.com/metalink/plsql/ml2_documents.showDocument?p_database_id=NOT&p_id=471687.1
    Note: 564045.1 - Oracle Application Object Library Mailer Component Test Setup Test
    https://metalink2.oracle.com/metalink/plsql/ml2_documents.showDocument?p_database_id=NOT&p_id=564045.1
    Note: 564043.1 - Oracle Application Object Library Workflow Agents/AQ Status Setup Test
    https://metalink2.oracle.com/metalink/plsql/ml2_documents.showDocument?p_database_id=NOT&p_id=564043.1

  • SMTP Authorization code for PHP Mail Form

    Can anyone help me in figuring out the correct way to incorporate the SMTP authentication into a form? I am having a lot of trouble in getting my forms to send with this format. My code for my php action page is below. I have my correct information where i included *******. Please let me know what i have wrong.
    CODE STARTS HERE
    <?php
    //new function
    $to = "*******";
    $nameto = "LTL Freight Shop";
    $from = "*******";
    $namefrom = "LTL Freight Shop";
    $subject = "Account Request";
    authSendEmail($from, $namefrom, $to, $nameto, $subject, $message);
    ?>
    <?php
    $recipient  = "*******";
    //$subject = "Account Request";
    $companyname = check_input($_POST['CompanyName'], "Enter your company name");
    $firstname  = check_input($_POST['FirstName'], "Enter your first name");
    $lastname  = check_input($_POST['LastName'], "Enter your last name");
    $phone  = check_input($_POST['PhoneNumber'], "Enter your phone number");
    $fax  = check_input($_POST['FaxNumber']);
    $email  = check_input($_POST['Email'], "Enter your email");
    $address  = check_input($_POST['StreetAddress'], "Enter your address");
    $city  = check_input($_POST['City'], "Enter your city");
    $state  = check_input($_POST['State'], "Enter your state");
    $zipcode  = check_input($_POST['ZipCode'], "Enter your zip code");
    $country  = check_input($_POST['Country'], "Enter your country");
    $yearsinbusiness  = check_input($_POST['YearsinBusiness'], "Enter your years in business");
    $typeofindustry  = check_input($_POST['TypeofIndustry'], "Enter your type of industry");
    $multiplelocations    = check_input($_POST['MultipleLocations']);
    $numberoflocations  = check_input($_POST['LocationsCount']);
    $ltl  = check_input($_POST['ServicesLTL']);
    $ftl  = check_input($_POST['ServicesFTL']);
    $domesticparcel  = check_input($_POST['ServicesDomesticParcel']);
    $intlparcel  = check_input($_POST['ServicesInternationalParcel']);
    $airfreight  = check_input($_POST['ServicesAirFreight']);
    $oceanfreight  = check_input($_POST['ServicesOceanFreight']);
    $other  = check_input($_POST['ServicesOther']);
    $none  = check_input($_POST['ServicesNone']);
    $volume  = check_input($_POST['TypicalVolume'], "Enter your typical volume");
    $carrier  = check_input($_POST['CurrentCarrier'], "Enter your current carrier");
    $class  = check_input($_POST['AverageClass'], "Enter your average class");
    $weight  = check_input($_POST['AverageWeight'], "Enter your average weight");
    $process   = check_input($_POST['Process']);
    $hearabout = check_input($_POST['HearAbout']);
    $comments = check_input($_POST['Comments']);
    if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
        show_error("E-mail address not valid");
    $message = "You have received an account request from:
    Company Name: $companyname
    First Name: $firstname
    Last Name: $lastname
    Phone Number: $phone
    Fax Number: $fax
    E-mail: $email
    Street Address: $address
    City: $city
    State: $state
    Zip Code: $zipcode
    Country: $country
    Years in Business: $yearsinbusiness
    Type of Industry: $typeofindustry
    Multiple Locations: $multiplelocations
    Number of Locations: $numberoflocations
    Services they use: $ltl, $ftl, $domesticparcel, $intlparcel, $airfreight, $oceanfreight, $other, $none
    Typical Volume: $volume
    Current Carrier: $carrier
    Average Class: $class
    Average Weight: $weight
    How they currently process: $process
    How they heard about us: $hearabout
    Comments: $comments
    End of message
    //ini_set("SMTP","smtp.emailsrvr.com");
    //ini_set("SMTP_PORT", 25);
    //ini_set("sendmail_from","*******");
    //mail($recipient, $subject, $message);
    function check_input($data, $problem='')
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        if ($problem && strlen($data) == 0)
            show_error($problem);
        return $data;
    function authSendEmail($from, $namefrom, $to, $nameto, $subject, $message)
    $smtpServer = "smtp.emailsrvr.com";
    $port = "25";
    $timeout = "30";
    $username = "********";
    $password = "********";
    $localhost = "smtp.emailsrvr.com";
    $newLine = "\r\n";
    $smtpConnect = fsockopen($smtpServer, $port, $errno, $errstr, $timeout);
    $smtpResponse = fgets($smtpConnect, 515);
    if(empty($smtpConnect))
    $output = "Failed to connect: $smtpResponse";
    return $output;
    else
    $logArray['connection'] = "Connected: $smtpResponse";
    fputs($smtpConnect,"AUTH LOGIN" . $newLine);
    $smtpResponse = fgets($smtpConnect, 515);
    $logArray['authrequest'] = "$smtpResponse";
    fputs($smtpConnect, base64_encode($username) . $newLine);
    $smtpResponse = fgets($smtpConnect, 515);
    $logArray['authusername'] = "$smtpResponse";
    fputs($smtpConnect, base64_encode($password) . $newLine);
    $smtpResponse = fgets($smtpConnect, 515);
    $logArray['authpassword'] = "$smtpResponse";
    fputs($smtpConnect, "HELO $localhost" . $newLine);
    $smtpResponse = fgets($smtpConnect, 515);
    $logArray['heloresponse'] = "$smtpResponse";
    fputs($smtpConnect, "MAIL FROM: $from" . $newLine);
    $smtpResponse = fgets($smtpConnect, 515);
    $logArray['mailfromresponse'] = "$smtpResponse";
    fputs($smtpConnect, "RCPT TO: $to" . $newLine);
    $smtpResponse = fgets($smtpConnect, 515);
    $logArray['mailtoresponse'] = "$smtpResponse";
    fputs($smtpConnect, "DATA" . $newLine);
    $smtpResponse = fgets($smtpConnect, 515);
    $logArray['data1response'] = "$smtpResponse";
    $headers = "MIME-Version: 1.0" . $newLine;
    $headers .= "Content-type: text/html; charset=iso-8859-1" . $newLine;
    $headers .= "To: $nameto <$to>" . $newLine;
    $headers .= "From: $namefrom <$from>" . $newLine;
    fputs($smtpConnect, "To: $to\nFrom: $from\nSubject: $subject\n$headers\n\n$message\n.\n");
    $smtpResponse = fgets($smtpConnect, 515);
    $logArray['data2response'] = "$smtpResponse";
    fputs($smtpConnect,"QUIT" . $newLine);
    $smtpResponse = fgets($smtpConnect, 515);
    $logArray['quitresponse'] = "$smtpResponse";
    function show_error($myError)
    ?>
        <html>
        <body>
        <b>Please correct the following error:</b><br />
        <?php echo $myError; ?>
        </body>
        </html>
    <?php
    exit();
    ?>

    I have tried the standard PHP mail function and it doesnt seem to work. Here is my most recent warning or error message.
    Warning: mail() [function.mail]: SMTP server response: 554 5.7.1 <*****>: Sender address rejected: Access denied in D:\inetpub\vhosts\ltlfreightshop.com\httpdocs\requestaccount.php on line 78
    I had the standard mailing set up but it wouldnt ever send and when i set up just the form, it requires the default email client. Am i wrong to assume that i need the SMTP authentication?
    I am not sure about the sockets being enabled. We currently outsource our web hosting and email hosting. I cannot find the phpinfo(), where would this be?
    Thanks,
    Ben

  • The SMTP Error Code from a message that was not sucessfully delivered ?

    hello,
    I'm developing an aplication that uses Java Mail and
    send emails, but I need to get the error code if this
    email was not sucessfully delivered, use
    mail.smtp.dsn.notify to destination return an email in case
    of failure.
    Thaks for your help.
    rania+

    Do you mean the SMTP server reply codes? These are the codes that are returned when the client tries passing the message to the server. The are from RFC 821 (http://www.ietf.org/rfc/rfc0821.txt).
    500 Syntax error, command unrecognized
    [This may include errors such as command line too long]
    501 Syntax error in parameters or arguments
    502 Command not implemented
    503 Bad sequence of commands
    504 Command parameter not implemented
    211 System status, or system help reply
    214 Help message
    [Information on how to use the receiver or the meaning of a
                particular non-standard command; this reply is useful only
                to the human user]
    220 <domain> Service ready
    221 <domain> Service closing transmission channel
    421 <domain> Service not available,
    closing transmission channel
    [This may be a reply to any command if the service knows it
                must shut down]
    250 Requested mail action okay, completed
    251 User not local; will forward to <forward-path>
    450 Requested mail action not taken: mailbox unavailable
    [E.g., mailbox busy]
    550 Requested action not taken: mailbox unavailable
    [E.g., mailbox not found, no access]
    451 Requested action aborted: error in processing
    551 User not local; please try <forward-path>
    452 Requested action not taken: insufficient system storage
    552 Requested mail action aborted: exceeded storage allocation
    553 Requested action not taken: mailbox name not allowed
    [E.g., mailbox syntax incorrect]
    354 Start mail input; end with <CRLF>.<CRLF>
    554 Transaction failed

  • Smtp asking to check network connctions yet no mail sent out only mailed?

    SMTP, under doctor, mail spins then says ck network connections?
    yet I can receive eML and I can browse the net via Safari what could be my problem?

    SMTP, under doctor, mail spins then says ck network connections?
    yet I can receive eML and I can browse the net via Safari what could be my problem?
    R U able to go into your mail alright via www.apple.com/mac (choose mac) then go to mail and try to login from there. See if you are able to connect that way by trying to send (which is where you seem to be having the problem i.e. smtp).
    {Code}
    RJ
    {Code}

  • I have one e-mail address that constantly hard bounces

    I have one e-mail address for a client that constantly returns an error of
    "An error occurred while sending mail. The mail server responded: <[email protected]> previously hard-bounced. Please check the message recipient "clients email address" and try again"
    I also look after the mail server for this user name and I have tried deleting the account and re entering but it makes no difference. Other e-mail clients donut seem to have this problem.
    Any ideas?
    g

    A soft bounce may mean that the mailbox if full., but a 550 error har bounce code sent from the server usually describes when the email address does not exist or is otherwise permanently not available.
    Perhaps due to a typo in the email address or that email address is no longer valid.
    Or maybe there have been several soft bounces that converted to a hard bounce.
    Could the server be blocking the sender email address (possibly as part of a spam defence system), so the email is not delivered to recipient if sent from that particular email address.

  • Marketing Emails to Staff Bouncing

    Hi everyone,
    Since using the marketing aspect of our website (www.retailsystemspl.com.au) we have been having issues sending out emails to internal staff.
    Basically, what I want to be able to do is send my marketing piece to all clients, and all of my staff so they know what information is being sent to clients - this way they can understand and process enquiries efficiently
    To do this I have created a staff marketing list containing the email addresses/info of staff , which is also included in the recipients stage.
    Whilst our email campaigns and test emails are working for clients, they are not coming through to my 8 staff.
    Now I don't fully understand this, but according to our IT guru  we thought that this may be an issue due to our remote DYNDWS address.
    We are now using a FQDN connection and still not recieving emails.
    I have looked at email bounces and below is a print screen of some staff members bounce reasons, -means nothing to me..but they all seem to bounce for the same reason..
    Has anyone else experienced this issue before? Any ideas or ways of resolving this?
    We are at a loss... :/
    Cheers!

    oops seeing as the image was distorted, here is the bounce code we get :
    Hard Bounce :Reporting-MTA: dns;relay-syd.worldsecuresystems.com X-PowerMTA-VirtualMTA: {default} Received-From-MTA: dns;sydsd-vm-mail-1.bc.adobe.com (172.26.170.23) Arrival-Date: Thu, 20 Sep 2012 08:06:16 +1000 Final-Recipient: rfc822;[email protected] Action: failed Status: 5.4.6 (routing loop detected) X-PowerMTA-BounceCategory: routing-errors

  • Developing a Email Cleint..Specfiying the SMTP Server

    Hello all,
    I am trying to develop an email client, for the sole purpose of sending mail(not reading).. That means i have to implement the SMTP part.. I have gone through the javamail api, but it requires a SMTP server to which the mail is sent...
    The problem is that i dont have an smtp server to specify.. Can some one please help me so that i can find some free smtp server (code, or server address) which i can use to send the mail..
    Thanks in advance

    STFW
    http://www.google.com/search?hl=en&lr=&ie=UTF-8&oe=utf-8&q=%22mail+server%22+free&btnG=Google+Search

  • Comcast SMTP not found

    Last night i spent 4 hrs trying to work with the account setup and i would always get to the outgoing mail server (SMTP). And it would always come back saying "SMTP server not found" I need help i talked to the comcast people and there is nothing wrong with me account registration or anything. I e en checked the SMTP server code and it was 587, the comcast website reccommended code. I need help!

    Were you essentially following these instructions?
    http://www.comcast.net/help/faq/index.jsp?faq=EmailMail_(Mac)17746
    DNS records indicate that the canonical name smtp.comcast.net is valid, and these numeric IP addresses are returned in response to a query using that name:
    smtp.comcast.net 63.240.77.77
    smtp.comcast.net 204.127.192.17
    smtp.comcast.net 204.127.200.17
    smtp.comcast.net 204.127.225.17
    smtp.comcast.net 216.148.227.147
    smtp.comcast.net 206.18.177.17
    It seems unlikely that the DNS servers you are tied to would fail to make these association, but try this:
    Instead of using the name smtp.comcast.net in the Outgoing (SMTP) Mail Server: field, insert 63.240.77.77 instead, and see if you can complete the account provisioning process. Any one of those six numeric addresses should allow you to create or configure a Comcast account properly.

  • Can't send mail to .Mac accounts

    I saw this problem posted before but the answer didn't solve it for me. I don't have a .Mac account but I use pop mail for my email from my web-based email. Every time I send to a [email protected] address, I get the following message from "Mail Delivery Subsystem" (charles is an example @mac.com address)
    The original message was received at Thu, 6 Sep 2007 09:46:33 -0700 (PDT)
    from smtpout09-04.prod.mesa1.secureserver.net [64.202.165.17]
    ----- The following addresses had permanent fatal errors -----
    <[email protected]>
    (reason: 550 5.1.1 unknown or illegal alias: [email protected])
    (expanded from: <[email protected]>)
    ----- Transcript of session follows -----
    ... while talking to smtp-bounce.mac.com.:
    DATA
    <<< 550 5.1.1 unknown or illegal alias: [email protected]
    550 5.1.1 <[email protected]>... User unknown
    <<< 554 5.5.0 No recipients have been specified.
    Reporting-MTA: dns; mac.com
    Received-From-MTA: DNS; smtpout09-04.prod.mesa1.secureserver.net
    Arrival-Date: Thu, 6 Sep 2007 09:46:33 -0700 (PDT)
    Final-Recipient: RFC822; [email protected]
    Action: failed
    Status: 5.1.1
    Remote-MTA: DNS; smtp-bounce.mac.com
    Diagnostic-Code: SMTP; 550 5.1.1 unknown or illegal alias: [email protected]
    Last-Attempt-Date: Thu, 6 Sep 2007 09:46:35 -0700 (PDT)

    This is only a guess, as there is no host "smtp-bounce.mac.com": your mailserver smtpout09-04.prod.mesa1.secureserver.net is currently listed at least at one blacklist service (take a look here http://tqmcube.com/cgi-bin/rbltqm?ip=64.202.165.17 to verify) as a spammer.
    I am not sure about the technology Apple uses to prevent SPAM, but it technically would be possible to check for listed servers before establishing a connection and saying "HELO" with a faked hostname (smtp-bounce.mac.com in that case) and bouncing all mail.
    The second possibility is, of course, that the given error "User unknown" is correct, and the user imply does not exist.
    Try figuring this out by sending mail to .Mac users using an alternative mail provider or SMTP-server.

  • PL/SQL Mail Utility :: Binary/Ascii/Cc/Bcc/FileDump

    I was working on my mail package and decided it was overtly complicated and
    stripped it down to its bare bones. Here is what I came up with. Built on a previous
    foundation of anothers work, I expanded the functionality considerably. You will find all
    the features I think that you will need regarding a mail routine. There is also a nice
    filedump routine included which makes very easy to create flat file dumps that you can
    then attach to your emails. There are a few pre-reqs in using this though :
    - 9iR2+
    - DBA_Directories defined as opposed to utl_file paths
    - Java Virtual Machine. Document can be found in “Note :105472.1 Setup, Configuration,
    and Use of the Java Virtual Machine” on metalink.
    As always, I welcome feedback and suggestions for improvement.
    Barry C
    http://www.myoracleportal.com
    CREATE OR REPLACE PACKAGE mail_tools
    AS
    -- SENDMAIL supports variable message length with/without attachments
    -- QUERY_SERVER allows you to check the status of a mail server to see if it is running
    -- DUMP_FLATFILE allows you to dump flat file data from query submitted
    -- Query Server to verify that the server is up and running.
    -- Connects, Noop Command is executed, Disconnect.
    -- GET_MAIL_ADDRESS is utilized in the SENDMAIL procedure
    -- Table 100-3 SMTP Reply Codes
    -- Reply Code
    -- Meaning
    -- 211 System status, or system help reply
    -- 214 Help message [Information on how to use the receiver or the meaning of a particular non-standard command; this reply is useful only to the human user]
    -- 220 <domain> Service ready
    -- 221 <domain> Service closing transmission channel
    -- 250 Requested mail action okay, completed
    -- 251 User not local; will forward to <forward-path>
    -- 252 OK, pending messages for node <node> started. Cannot VRFY user (e.g., info is not local), but will take message for this user and attempt delivery.
    -- 253 OK, <messages> pending messages for node <node> started
    -- 354 Start mail input; end with <CRLF>.<CRLF>
    -- 355 Octet-offset is the transaction offset
    -- 421 <domain> Service not available, closing transmission channel (This may be a reply to any command if the service knows it must shut down.)
    -- 450 Requested mail action not taken: mailbox unavailable [for example, mailbox busy]
    -- 451 Requested action aborted: local error in processing
    -- 452 Requested action not taken: insufficient system storage
    -- 453 You have no mail.
    -- 454 TLS not available due to temporary reason. Encryption required for requested authentication mechanism.
    -- 458 Unable to queue messages for node <node>
    -- 459 Node <node> not allowed: reason
    -- 500 Syntax error, command unrecognized (This may include errors such as command line too long.)
    -- 501 Syntax error in parameters or arguments
    -- 502 Command not implemented
    -- 503 Bad sequence of commands
    -- 504 Command parameter not implemented
    -- 521 <Machine> does not accept mail.
    -- 530 Must issue a STARTTLS command first. Encryption required for requested authentication mechanism.
    -- 534 Authentication mechanism is too weak.
    -- 538 Encryption required for requested authentication mechanism.
    -- 550 Requested action not taken: mailbox unavailable [for , mailbox not found, no access]
    -- 551 User not local; please try <forward-path>
    -- 552 Requested mail action aborted: exceeded storage allocation
    -- 553 Requested action not taken: mailbox name not allowed [for example, mailbox syntax incorrect]
    -- 554 Transaction failed
    This version allows for a customized seperator value. Using this function will allow you to
    perform fixed width flat files by defining '' for no seperator and then RPAD/LPAD your columns as necessary.
    Or use whatever seperator you wish to use, pipe, space, zeros, etc.
       --  Example : This will generate a flat file which tabbed seperated
    -- DECLARE
    --    l_rows   NUMBER;
    --    l_sql    VARCHAR2(32000);
    -- BEGIN
    --    l_sql := '
    -- SELECT   rpad(hou.NAME,70) udn_desc
    -- ,        rpad(pcak.segment1,6) coid
    -- ,        rpad(pcak.segment2,4) udn
    --     FROM hr_all_organization_units hou, hr.pay_cost_allocation_keyflex pcak
    --    WHERE TRUNC (SYSDATE) BETWEEN hou.date_from
    --                              AND NVL (hou.date_to, ''31-DEC-4712'')
    --      AND pcak.cost_allocation_keyflex_id = hou.cost_allocation_keyflex_id
    -- GROUP BY pcak.segment1, pcak.segment2, hou.NAME
    -- ORDER BY 1, 2, 3
    --    l_rows :=
    --       dump_flatfile
    --          (p_query          =>
    -- ,         p_dir            => 'INTF000_TABLES'
    -- ,         p_filename       => 'test.csv'
    -- ,       p_separator     => '     ' -- <= tabbed 5 spaces between each column
    -- ,       p_max_linesize   => 32000
    -- ,       p_mode       => 'w' -- (w)rite mode or (a)ppend mode
    -- END;
       FUNCTION dump_flatfile (
          p_query                    IN       VARCHAR2
    ,     p_dir                      IN       VARCHAR2
    ,     p_filename                 IN       VARCHAR2
    ,     p_separator                IN       VARCHAR2
    ,     p_headers                  IN       BOOLEAN DEFAULT FALSE
    ,     p_trailing_separator       IN       BOOLEAN DEFAULT FALSE
    ,     p_max_linesize             IN       NUMBER DEFAULT 32000
    ,     p_mode                     IN       VARCHAR2 DEFAULT 'w' )
          RETURN NUMBER;
       FUNCTION get_mail_address (
          addr_list                  IN OUT   VARCHAR2 )
          RETURN VARCHAR2;
       FUNCTION smtp_command (
          command                    IN       VARCHAR2
    ,     ok                         IN       VARCHAR2 DEFAULT '250'
    ,     code                       OUT      VARCHAR2
    ,     DEBUG                               NUMBER DEFAULT 0 )
          RETURN BOOLEAN;
       FUNCTION query_server (
          smtp_server                         VARCHAR2
    ,     smtp_server_port                    PLS_INTEGER DEFAULT 25
    ,     DEBUG                               NUMBER DEFAULT 0 )
          RETURN BOOLEAN;
    This procedure uses the UTL_TCP package to send an email message.
    Up to three file names may be specified as attachments.
    Written: Dave Wotton, 14/6/01 (Cambridge UK)
    This script comes with no warranty or support. You are free to
    modify it as you wish, but please retain an acknowledgement of
    my original authorship.
    Amended: Dave Wotton, 10/7/01
    Now uses the utl_smtp.write_data() method to send the message,
    eliminating the 32Kb message size constraint imposed by the
    utl_smtp.data() procedure.
    Amended: Dave Wotton, 20/7/01
    Increased the v_line variable, which holds the file attachment
    lines from 400 to 1000 bytes. This is the maximum supported
    by RFC2821, The Simple Mail Transfer Protocol specification.
    Amended: Dave Wotton, 24/7/01
    Now inserts a blank line before each MIME boundary line. Some
    mail-clients require this.
    Amended: Dave Wotton, 4/10/01
    Introduced a 'debug' parameter. Defaults to 0. If set to
    non-zero then errors in opening files for attaching are
    reported using dbms_output.put_line.
    Include code to hand MS Windows style pathnames.
    Amended: Barry Chase, 4/29/03
    Added Priority to procedure and also X-Mailer ID.
    Removed restrictions for email size limitation as well.
    Emails are now formatted text messages, meaning you can
    write your message in html format.
    And finally, changed from using UTL_SMTP to UTL_TCP instead.
    Amended: Barry Chase 11/10/2003
    Added session timeout of 4 minutes to prevent hanging server connections
    Amended: Barry Chase 12/04/2003
    Added Date String so that it represents timezone of originating server
    p_datestring
    Amended: Barry Chase 03/01/2004
    Added functionality to support binary attachments and remote attachments.
    Its about 98% complete. Not work perfectly yet. Still trying to figure out
    encoding to base64 or mime. Have a good start on it though.
    04/12/2004
    BCHASE :: Binary Support is fully functional now.
    09/01/2005
    BCHASE :: Modified attachment directories to use DBA_DIRECTORIES instead
    of UTL_DIR in the Oracle initialization file.
    02/22/2006
    BCHASE :: Added variable length message email support (CLOB)
    04/21/2006
    BCHASE :: Expanded functionality to include Cc and Bcc
    Also removed redundant calls from package. The single
    mail_files command will handle flat files and binary files such as zip/pdf/etc.
    SMTP Server and SMTP Server Port are parameters on the sendmail procedure now
    as well.
    Refer to http://home.clara.net/dwotton/dba/oracle_smtp.htm for more
    details on the original source code.
    For information on the enhanced mail_tools package as provided by Barry
    Chase, refer to http://www.myoracleportal.com
       /* Retrieves local binary file from database server.
        * using DBMS_LOB commands and stores into BLOB
        * return BLOB
       FUNCTION get_local_binary_data (
          p_dir                      IN       VARCHAR2
    ,     p_file                     IN       VARCHAR2 )
          RETURN BLOB;
    /* Supports binary attachments and message of variable length. Uses CLOB.*/
    -- DECLARE
    -- t_blob BLOB;
    -- BEGIN
    -- Use the get_local_binary_data to collect your BLOB from the filesystem
    -- or just load from a table where your BLOB is stored at, then just pass
    -- as t_blob on the binaryfile parameter below. Remember to provide an
    -- appropriate filename. Optionally, you can leave filename NULL and pass
    -- the binaryfile parameter as EMPTY_BLOB() to send an email without an
    -- attachment.
    --   t_blob :=
    --    mail_tools.get_local_binary_data
    --                   ( p_dir =>                         'INTF0047_TABLES'
    --,                    p_file =>                        'test_file1.csv' );
    --    mail_tools.sendmail
    --             ( smtp_server =>                   'your.smtp.server'
    -- ,             smtp_server_port =>              25
    -- ,             from_name =>                     'Email Address of Sender'
    -- ,             to_name =>                       'list of TO email addresses separated by commas (,)'
    -- ,             cc_name =>                       'list of CC email addresses separated by commas (,)'
    -- ,             bcc_name =>                      'list of BCC email addresses separated by commas (,)'
    -- ,             subject =>                       'Some brief Subject'
    -- ,             MESSAGE =>                       'Your message goes here. Can include HTML code.'
    -- ,             priority =>                      '1-5 1 being the highest priority and 3 normal priority'
    -- ,             filename =>                      'your.filename.txt or leave NULL'
    -- ,             binaryfile =>                    'your blob is passed here otherwise leave as EMPTY_BLOB()
    -- ,             DEBUG =>                         'Default is DBMS output otherwise pass a 1 to disable );
    -- END;
       PROCEDURE sendmail (
          smtp_server                         VARCHAR2
    ,     smtp_server_port                    PLS_INTEGER DEFAULT 25
    ,     from_name                           VARCHAR2
    ,     to_name                             VARCHAR2
    ,     cc_name                             VARCHAR2 DEFAULT NULL
    ,     bcc_name                            VARCHAR2 DEFAULT NULL
    ,     subject                             VARCHAR2
    ,     MESSAGE                             CLOB
    ,     priority                            PLS_INTEGER DEFAULT NULL
    ,     filename                            VARCHAR2 DEFAULT NULL
    ,     binaryfile                          BLOB DEFAULT EMPTY_BLOB ( )
    ,     DEBUG                               NUMBER DEFAULT 0 );
       v_parm_value                  VARCHAR2 ( 4000 );
       lbok                          BOOLEAN;
       v_smtp_server                 VARCHAR2 ( 50 );
       v_smtp_server_port            NUMBER := 25;
       crlf                          VARCHAR2 ( 10 ) := utl_tcp.crlf;
       conn                          utl_tcp.connection;
       p_debug_marker                PLS_INTEGER := 0;
       rc                            INTEGER;
       p_from_name                   VARCHAR2 ( 100 );
       p_to_name                     VARCHAR2 ( 4000 );
       p_cc_name                     VARCHAR2 ( 4000 );
       p_bcc_name                    VARCHAR2 ( 4000 );
       p_subject                     VARCHAR2 ( 150 );
       tx_timeout                    PLS_INTEGER := 240;
                                                      -- 240 Seconds (4 minutes);
       p_datestring                  VARCHAR2 ( 100 )
          :=    'Date: '
             || TO_CHAR ( SYSDATE, 'MM/DD/RR HH:MI AM' )
             || ' '
             || DBTIMEZONE
             || ' '
             || '(GMT'
             || DBTIMEZONE
             || ')';
       -- Customize the signature that will appear in the email's MIME header.
       -- Useful for versioning.
       mailer_id            CONSTANT VARCHAR2 ( 256 ) := 'Mailer by Oracle UTL_TCP';
       max_base64_line_width CONSTANT PLS_INTEGER := 76 / 4 * 3;
    END;
    CREATE OR REPLACE PACKAGE BODY mail_tools
    IS
       PROCEDURE print_output (
          p_message                  IN       VARCHAR2 )
       IS
       BEGIN
          dbms_output.put_line ( SUBSTR ( p_message
    ,                                     1
    ,                                     250 ));
          IF LENGTH ( p_message ) > 250
          THEN
             dbms_output.put_line ( SUBSTR ( p_message
    ,                                        251
    ,                                        500 ));
          END IF;
          IF LENGTH ( p_message ) > 500
          THEN
             dbms_output.put_line ( SUBSTR ( p_message
    ,                                        501
    ,                                        750 ));
          END IF;
          IF LENGTH ( p_message ) > 750
          THEN
             dbms_output.put_line ( SUBSTR ( p_message
    ,                                        751
    ,                                        1000 ));
          END IF;
       EXCEPTION
          WHEN OTHERS
          THEN
             NULL;               -- Ignore errors... protect buffer overflow's etc.
       END print_output;
       FUNCTION dump_flatfile (
          p_query                    IN       VARCHAR2
    ,     p_dir                      IN       VARCHAR2
    ,     p_filename                 IN       VARCHAR2
    ,     p_separator                IN       VARCHAR2
    ,     p_headers                  IN       BOOLEAN DEFAULT FALSE
    ,     p_trailing_separator       IN       BOOLEAN DEFAULT FALSE
    ,     p_max_linesize             IN       NUMBER DEFAULT 32000
    ,     p_mode                     IN       VARCHAR2 DEFAULT 'w' )
          RETURN NUMBER
       IS
          l_output                      utl_file.file_type;
          l_thecursor                   INTEGER DEFAULT dbms_sql.open_cursor;
          l_columnvalue                 VARCHAR2 ( 4000 );
          l_status                      INTEGER;
          l_colcnt                      NUMBER DEFAULT 0;
          l_cnt                         NUMBER DEFAULT 0;
          l_separator                   VARCHAR2 ( 10 ) DEFAULT '';
          l_line                        LONG;
          l_desctbl                     dbms_sql.desc_tab;
          v_sqlerrm                     VARCHAR2 ( 32000 );
          l_mode                        CHAR ( 1 ) := 'w';
       BEGIN
          IF p_mode NOT IN ( 'w', 'a' )
          THEN
             l_mode := 'w';
          ELSE
             l_mode := p_mode;
          END IF;
          l_output := utl_file.fopen ( p_dir
    ,                                  p_filename
    ,                                  l_mode
    ,                                  p_max_linesize );
          dbms_sql.parse ( l_thecursor
    ,                      p_query
    ,                      dbms_sql.native );
          dbms_sql.describe_columns ( l_thecursor
    ,                                 l_colcnt
    ,                                 l_desctbl );
          FOR i IN 1 .. l_colcnt
          LOOP
             dbms_sql.define_column ( l_thecursor
    ,                                 i
    ,                                 l_columnvalue
    ,                                 4000 );
             IF ( l_desctbl ( i ).col_type = 2 )                   /* number type */
             THEN
                l_desctbl ( i ).col_max_len := l_desctbl ( i ).col_precision + 2;
             ELSIF ( l_desctbl ( i ).col_type = 12 )                 /* date type */
             THEN
    /* length of my date format */
                l_desctbl ( i ).col_max_len := 20;
             ELSIF ( l_desctbl ( i ).col_type = 8 )                  /* LONG type */
             THEN
                l_desctbl ( i ).col_max_len := 2000;
             END IF;
             IF p_headers
             THEN
                utl_file.put ( l_output, l_separator || l_desctbl ( i ).col_name );
                l_separator := p_separator;
             END IF;
          END LOOP;
          IF p_trailing_separator
          THEN
             utl_file.put ( l_output, l_separator );
          END IF;
          IF p_headers
          THEN
             utl_file.new_line ( l_output );
          END IF;
          l_status := dbms_sql.EXECUTE ( l_thecursor );
          LOOP
             EXIT WHEN ( dbms_sql.fetch_rows ( l_thecursor ) <= 0 );
             l_line := NULL;
             l_separator := '';
             FOR i IN 1 .. l_colcnt
             LOOP
                dbms_sql.COLUMN_VALUE ( l_thecursor
    ,                                   i
    ,                                   l_columnvalue );
                IF NVL ( INSTR ( l_columnvalue, ',' ), 0 ) = 0
                THEN
                   NULL;
                ELSE
                   l_columnvalue := '"' || l_columnvalue || '"';
                END IF;
                utl_file.put ( l_output, l_separator || l_columnvalue );
                l_separator := p_separator;
             END LOOP;
             IF p_trailing_separator
             THEN
                utl_file.put ( l_output, l_separator );
             END IF;
             utl_file.new_line ( l_output );
             l_cnt := l_cnt + 1;
          END LOOP;
          dbms_sql.close_cursor ( l_thecursor );
          utl_file.fclose ( l_output );
          RETURN l_cnt;
       EXCEPTION
          WHEN NO_DATA_FOUND
          THEN
             dbms_output.put_line ( 'NO_DATA_FOUND' );
             utl_file.fclose ( l_output );
             RETURN l_cnt;
          WHEN utl_file.invalid_path
          THEN
             dbms_output.put_line ( 'UTL_FILE.INVALID_PATH' );
             utl_file.fclose ( l_output );
             RETURN l_cnt;
          WHEN utl_file.read_error
          THEN
             dbms_output.put_line ( 'UTL_FILE.READ_ERROR' );
             utl_file.fclose ( l_output );
             RETURN l_cnt;
          WHEN utl_file.write_error
          THEN
             dbms_output.put_line ( 'UTL_FILE.WRITE_ERROR' );
             utl_file.fclose ( l_output );
             RETURN l_cnt;
          WHEN utl_file.invalid_mode
          THEN
             dbms_output.put_line ( 'UTL_FILE.INVALID_MODE' );
             utl_file.fclose ( l_output );
             RETURN l_cnt;
          WHEN utl_file.invalid_filehandle
          THEN
             dbms_output.put_line ( 'UTL_FILE.INVALID_FILEHANDLE' );
             utl_file.fclose ( l_output );
             RETURN l_cnt;
          WHEN utl_file.invalid_operation
          THEN
             dbms_output.put_line ( 'UTL_FILE.INVALID_OPERATION' );
             utl_file.fclose ( l_output );
             RETURN l_cnt;
          WHEN utl_file.internal_error
          THEN
             dbms_output.put_line ( 'UTL_FILE.INTERNAL_ERROR' );
             utl_file.fclose ( l_output );
             RETURN l_cnt;
          WHEN utl_file.invalid_maxlinesize
          THEN
             dbms_output.put_line ( 'UTL_FILE.INVALID_MAXLINESIZE' );
             utl_file.fclose ( l_output );
             RETURN l_cnt;
          WHEN VALUE_ERROR
          THEN
             dbms_output.put_line ( 'UTL_FILE.VALUE_ERROR' );
             utl_file.fclose ( l_output );
             RETURN l_cnt;
          WHEN OTHERS
          THEN
             hum_do.default_exception ( 'ERROR in dump_csv : ' );
             utl_file.fclose ( l_output );
             RETURN l_cnt;
       END dump_flatfile;
       -- Return the next email address in the list of email addresses, separated
       -- by either a "," or a ";".  The format of mailbox may be in one of these:
       --   someone@some-domain
       --   "Someone at some domain" <someone@some-domain>
       --   Someone at some domain <someone@some-domain>
       FUNCTION get_mail_address (
          addr_list                  IN OUT   VARCHAR2 )
          RETURN VARCHAR2
       IS
          addr                          VARCHAR2 ( 256 );
          i                             PLS_INTEGER;
          FUNCTION lookup_unquoted_char (
             str                        IN       VARCHAR2
    ,        chrs                       IN       VARCHAR2 )
             RETURN PLS_INTEGER
          AS
             c                             VARCHAR2 ( 5 );
             i                             PLS_INTEGER;
             len                           PLS_INTEGER;
             inside_quote                  BOOLEAN;
          BEGIN
             inside_quote := FALSE;
             i := 1;
             len := LENGTH ( str );
             WHILE ( i <= len )
             LOOP
                c := SUBSTR ( str
    ,                         i
    ,                         1 );
                IF ( inside_quote )
                THEN
                   IF ( c = '"' )
                   THEN
                      inside_quote := FALSE;
                   ELSIF ( c = '\' )
                   THEN
                      i := i + 1;
                   -- Skip the quote character
                   END IF;
                   GOTO next_char;
                END IF;
                IF ( c = '"' )
                THEN
                   inside_quote := TRUE;
                   GOTO next_char;
                END IF;
                IF ( INSTR ( chrs, c ) >= 1 )
                THEN
                   RETURN i;
                END IF;
                <<next_char>>
                i := i + 1;
             END LOOP;
             RETURN 0;
          END;
       BEGIN
          addr_list := LTRIM ( addr_list );
          i := lookup_unquoted_char ( addr_list, ',;' );
          IF ( i >= 1 )
          THEN
             addr := SUBSTR ( addr_list
    ,                         1
    ,                         i - 1 );
             addr_list := SUBSTR ( addr_list, i + 1 );
          ELSE
             addr := addr_list;
             addr_list := '';
          END IF;
          i := lookup_unquoted_char ( addr, '<' );
          IF ( i >= 1 )
          THEN
             addr := SUBSTR ( addr, i + 1 );
             i := INSTR ( addr, '>' );
             IF ( i >= 1 )
             THEN
                addr := SUBSTR ( addr
    ,                            1
    ,                            i - 1 );
             END IF;
          END IF;
          RETURN addr;
       END;
       FUNCTION smtp_command (
          command                    IN       VARCHAR2
    ,     ok                         IN       VARCHAR2 DEFAULT '250'
    ,     code                       OUT      VARCHAR2
    ,     DEBUG                               NUMBER DEFAULT 0 )
          RETURN BOOLEAN
       IS
          response                      VARCHAR2 ( 3 );
          p_output_message              VARCHAR2 ( 255 );
          len                           PLS_INTEGER;
          PRAGMA AUTONOMOUS_TRANSACTION;
       BEGIN
          len := utl_tcp.write_line ( conn, command );
          p_output_message := SUBSTR ( utl_tcp.get_line ( conn, TRUE )
    ,                                  1
    ,                                  255 );
          response := SUBSTR ( p_output_message
    ,                          1
    ,                          3 );
          p_output_message :=
                             SUBSTR ( command || ' - ' || p_output_message
    ,                                 1
    ,                                 255 );
          IF DEBUG = 1
          THEN                                                          -- No Output
             NULL;
          ELSE                                          -- Then DBMS_OUTPUT messages
             print_output ( p_output_message );
          END IF;
          IF ( response <> ok )
          THEN
             code := response;
             RETURN FALSE;
          ELSE
             code := response;
             RETURN TRUE;
          END IF;
       EXCEPTION
          WHEN OTHERS
          THEN
             p_output_message := SQLCODE || ' - ' || SQLERRM;
             code := p_output_message;
             RETURN FALSE;
       END smtp_command;
       FUNCTION query_server (
          smtp_server                         VARCHAR2
    ,     smtp_server_port                    PLS_INTEGER DEFAULT 25
    ,     DEBUG                               NUMBER DEFAULT 0 )
          RETURN BOOLEAN
       IS
          p_output_message              VARCHAR2 ( 255 );
          PRAGMA AUTONOMOUS_TRANSACTION;
          err_noop                      EXCEPTION;    -- SMTP code 250 not received
          err_server_reject             EXCEPTION;
       -- SMTP code 421 means rejected
       BEGIN
          v_smtp_server := smtp_server;
          v_smtp_server_port := smtp_server_port;
    -- Open the SMTP connection ...
          conn :=
             utl_tcp.open_connection ( remote_host =>                   v_smtp_server
    ,                                  remote_port =>                   v_smtp_server_port
    ,                                  tx_timeout =>                    tx_timeout );
          ----- OPEN SMTP PORT CONNECTION
          rc := utl_tcp.write_line ( conn, 'HELO ' || v_smtp_server );
                -- This will return a 250 OK response if your connection is valid
    -- Initial handshaking ...
          ----- PERFORMS HANDSHAKING WITH SMTP SERVER
          p_output_message := utl_tcp.get_line ( conn, TRUE );
          IF DEBUG = 1
          THEN                                                          -- No Output
             NULL;
          ELSE                                          -- Then DBMS_OUTPUT messages
             print_output ( p_output_message );
          END IF;
          IF SUBSTR ( p_output_message
    ,                 1
    ,                 3 ) = '421'
          THEN
             RAISE err_server_reject;
          END IF;
          -- NOOP THE SERVER
          rc := utl_tcp.write_line ( conn, 'NOOP' );
                -- This will return a 250 OK response if your connection is valid
    -- Initial handshaking ...
          ----- PERFORMS NOOP WITH SMTP SERVER
          p_output_message := utl_tcp.get_line ( conn, TRUE );
          IF DEBUG = 1
          THEN                                                          -- No Output
             NULL;
          ELSE                                          -- Then DBMS_OUTPUT messages
             print_output ( p_output_message );
          END IF;
          IF SUBSTR ( p_output_message
    ,                 1
    ,                 3 ) <> '250'
          THEN
             RAISE err_noop;
          END IF;
          rc := utl_tcp.write_line ( conn, 'QUIT' );
          ----- ENDS EMAIL TRANSACTION
          BEGIN
             FOR i_idx IN 1 .. 100
             LOOP
                p_output_message := utl_tcp.get_line ( conn, TRUE );
                IF DEBUG = 1
                THEN                                                   -- No Output
                   NULL;
                ELSE                                    -- Then DBMS_OUTPUT messages
                   print_output ( p_output_message );
                END IF;
             END LOOP;
          EXCEPTION
             WHEN OTHERS
             THEN
                IF DEBUG = 1
                THEN                                                   -- No Output
                   NULL;
                ELSE                                    -- Then DBMS_OUTPUT messages
                   print_output ( p_output_message );
                END IF;
          END;
          utl_tcp.close_connection ( conn );        ----- CLOSE SMTP PORT CONNECTION
          RETURN TRUE;
       EXCEPTION
          WHEN err_server_reject
          THEN
             print_output (    'ERROR -'
                            || ' Server Rejected Connection ::'
                            || ' SERVER_MSG := '
                            || p_output_message );
             RETURN FALSE;
          WHEN err_noop
          THEN
             print_output (    'ERROR -'
                            || ' NOOP Check Failed ::'
                            || ' SERVER_MSG := '
                            || p_output_message );
             utl_tcp.close_connection ( conn );     ----- CLOSE SMTP PORT CONNECTION
             RETURN FALSE;
       END query_server;
       FUNCTION get_local_binary_data (
          p_dir                      IN       VARCHAR2
    ,     p_file                     IN       VARCHAR2 )
          RETURN BLOB
       IS
          l_bfile                       BFILE;
          l_data                        BLOB;
          l_dbdir                       VARCHAR2 ( 100 ) := p_dir;
       BEGIN
          dbms_lob.createtemporary ( lob_loc =>                       l_data
    ,                                CACHE =>                         TRUE
    ,                                dur =>                           dbms_lob.CALL );
          l_bfile := BFILENAME ( l_dbdir, p_file );
          dbms_lob.fileopen ( l_bfile, dbms_lob.file_readonly );
          dbms_lob.loadfromfile ( l_data
    ,                             l_bfile
    ,                             dbms_lob.getlength ( l_bfile ));
          dbms_lob.fileclose ( l_bfile );
          RETURN l_data;
       EXCEPTION
          WHEN OTHERS
          THEN
             print_output (    'Error during GET_LOCAL_BINARY_DATA :: '
                            || SQLCODE
                            || ' - '
                            || SQLERRM );
             dbms_lob.fileclose ( l_bfile );
             RAISE;
       END get_local_binary_data;
       PROCEDURE attach_base64 (
          conn                       IN OUT NOCOPY utl_tcp.connection
    ,     DATA                       IN       BLOB )
       IS
          i                             PLS_INTEGER;
          len                           PLS_INTEGER;
          l_result                      PLS_INTEGER;
          l_buffer                      RAW ( 32767 );
          l_pos                         INTEGER := 1;
          l_blob_len                    INTEGER;
          l_amount                      BINARY_INTEGER := 32767;
          req                           utl_http.req;
          resp                          utl_http.resp;
          pdata                         RAW ( 200 );
       BEGIN
          -- Split the Base64-encoded attachment into multiple lines
          -- In writing Base-64 encoded text following the MIME format below,
          -- the MIME format requires that a long piece of data must be splitted
          -- into multiple lines and each line of encoded data cannot exceed
          -- 80 characters, including the new-line characters. Also, when
          -- splitting the original data into pieces, the length of each chunk
          -- of data before encoding must be a multiple of 3, except for the
          -- last chunk. The constant MAX_BASE64_LINE_WIDTH
          -- (76 / 4 * 3 = 57) is the maximum length (in bytes) of each chunk
          -- of data before encoding.
          l_blob_len := dbms_lob.getlength ( DATA );
          WHILE l_pos < l_blob_len
          LOOP
             l_amount := max_base64_line_width;
             dbms_lob.READ ( DATA
    ,                        l_amount
    ,                        l_pos
    ,                        l_buffer );
             rc := utl_tcp.write_raw ( conn, utl_encode.base64_encode ( l_buffer ));
             utl_tcp.FLUSH ( conn );
             l_pos := l_pos + max_base64_line_width;
             rc := utl_tcp.write_line ( conn, crlf );
          END LOOP;
       END attach_base64;
       PROCEDURE sendmail (
          smtp_server                         VARCHAR2
    ,     smtp_server_port                    PLS_INTEGER DEFAULT 25
    ,     from_name                           VARCHAR2
    ,     to_name                             VARCHAR2
    ,     cc_name                             VARCHAR2 DEFAULT NULL
    ,     bcc_name                            VARCHAR2 DEFAULT NULL
    ,     subject                             VARCHAR2
    ,     MESSAGE                             CLOB
    ,     priority                            PLS_INTEGER DEFAULT NULL
    ,     filename                            VARCHAR2 DEFAULT NULL
    ,     binaryfile                          BLOB DEFAULT EMPTY_BLOB ( )
    ,     DEBUG                               NUMBER DEFAULT 0 )
       IS
          pos                           PLS_INTEGER := 1;
          bytes_o_data         CONSTANT PLS_INTEGER := 32767;
          offset                        PLS_INTEGER := bytes_o_data;
          msg_length           CONSTANT PLS_INTEGER
                                                  := dbms_lob.getlength ( MESSAGE );
          v_line                        VARCHAR2 ( 32767 );
          i                             BINARY_INTEGER;
          v_slash_pos                   NUMBER;
          my_recipients                 VARCHAR2 ( 32767 );
          p_recipient_count             PLS_INTEGER := 0;
          p_output_message              VARCHAR2 ( 2000 );
          PRAGMA AUTONOMOUS_TRANSACTION;
          err_server_reject             EXCEPTION;
          -- SMTP code 421 means rejected
          err_message_send              EXCEPTION;         -- SMTP code must be 250
          err_end_of_input              EXCEPTION;
       -- Used to signify last line of input retrieved
          l_result                      PLS_INTEGER;
          l_buffer_b                    RAW ( 32767 );
          l_amount                      BINARY_INTEGER := 32767;
          l_pos                         INTEGER := 1;
          l_blob_len                    INTEGER;
          l_blob                        BLOB;
          g_debug                       BOOLEAN := TRUE;
          i_base64                      PLS_INTEGER;
          len_base64                    PLS_INTEGER;
       BEGIN
          v_smtp_server := smtp_server;
          v_smtp_server_port := smtp_server_port;
          l_blob := binaryfile;
    -- Open the SMTP connection ...
          conn :=
             utl_tcp.open_connection ( remote_host =>                   v_smtp_server
    ,                                  remote_port =>                   v_smtp_server_port
    ,                                  tx_timeout =>                    tx_timeout );
          ----- OPEN SMTP PORT CONNECTION
          rc := utl_tcp.write_line ( conn, 'HELO ' || v_smtp_server );
    -- Initial handshaking ...
          ----- PERFORMS HANDSHAKING WITH SMTP SERVER
          p_output_message := utl_tcp.get_line ( conn, TRUE );
          IF DEBUG = 1
          THEN                                                          -- No Output
             NULL;
          ELSE                                          -- Then DBMS_OUTPUT messages
             print_output ( p_output_message );
          END IF;
          IF SUBSTR ( p_output_message
    ,                 1
    ,                 3 ) = '421'
          THEN
             RAISE err_server_reject;
          ELSE
    --      DBMS_OUTPUT.put_line (UTL_TCP.get_line (conn, TRUE));
             rc := utl_tcp.write_line ( conn, 'MAIL FROM: ' || from_name );
             ----- MBOX SENDING THE EMAIL
             p_output_message := utl_tcp.get_line ( conn, TRUE );
             IF DEBUG = 1
             THEN                                                      -- No Output
                NULL;
             ELSE                                       -- Then DBMS_OUTPUT messages
                print_output ( p_output_message );
             END IF;
    --      DBMS_OUTPUT.put_line (UTL_TCP.get_line (conn, TRUE));
             --      rc := UTL_TCP.write_line (conn, 'RCPT TO: ' || to_name);
             -- Specify recipient(s) of the email.
             my_recipients := to_name;
             WHILE ( my_recipients IS NOT NULL )
             LOOP
                BEGIN
                   rc :=
                      utl_tcp.write_line ( conn
    ,                                         'RCPT TO: '
                                           || get_mail_address ( my_recipients ));
                   p_recipient_count := p_recipient_count + 1;
                END;
             END LOOP;
    --         DBMS_OUTPUT.put_line ('RCPT TO: COUNT ' || p_recipient_count);
             ----- MBOX RECV THE EMAIL
             p_output_message := utl_tcp.get_line ( conn, TRUE );
             IF DEBUG = 1
             THEN                                                       -- No Output
                NULL;
             ELSE                                       -- Then DBMS_OUTPUT messages
                print_output ( p_output_message );
             END IF;
    --      DBMS_OUTPUT.put_line (UTL_TCP.get_line (conn, TRUE));
             --      rc := UTL_TCP.write_line (conn, 'RCPT TO: ' || cc_name);
             -- Specify cc recipient(s) of the email.
             my_recipients := cc_name;
             WHILE ( my_recipients IS NOT NULL )
             LOOP
                BEGIN
                   rc :=
                      utl_tcp.write_line ( conn
    ,                                         'RCPT TO: '
                                           || get_mail_address ( my_recipients ));
                   p_recipient_count := p_recipient_count + 1;
                END;
             END LOOP;
    --         DBMS_OUTPUT.put_line ('RCPT TO: COUNT ' || p_recipient_count);
             ----- MBOX RECV THE EMAIL
             p_output_message := utl_tcp.get_line ( conn, TRUE );
             IF DEBUG = 1
             THEN                                                       -- No Output
                NULL;
             ELSE                                       -- Then DBMS_OUTPUT messages
                print_output ( p_output_message );
             END IF;
    --      DBMS_OUTPUT.put_line (UTL_TCP.get_line (conn, TRUE));
             --      rc := UTL_TCP.write_line (conn, 'RCPT TO: ' || bcc_name);
             -- Specify bcc recipient(s) of the email.
             my_recipients := bcc_name;
             WHILE ( my_recipients IS NOT NULL )
             LOOP
                BEGIN
                   rc :=
                      utl_tcp.write_line ( conn
    ,                                         'RCPT TO: '
                                           || get_mail_address ( my_recipients ));
                   p_recipient_count := p_recipient_count + 1;
                END;
             END LOOP;
    --         DBMS_OUTPUT.put_line ('RCPT TO: COUNT ' || p_recipient_count);
             ----- MBOX RECV THE EMAIL
             p_output_message := utl_tcp.get_line ( conn, TRUE );
             IF DEBUG = 1
             THEN                                                       -- No Output
                NULL;
             ELSE                                       -- Then DBMS_OUTPUT messages
                print_output ( p_output_message );
             END IF;
    --      DBMS_OUTPUT.put_line (UTL_TCP.get_line (conn, TRUE));
             rc := utl_tcp.write_line ( conn, 'DATA' );
             ----- EMAIL MSG BODY START
             p_output_message := utl_tcp.get_line ( conn, TRUE );
             IF DEBUG = 1
             THEN                                                       -- No Output
                NULL;
             ELSE                                       -- Then DBMS_OUTPUT messages
                print_output ( p_output_message );
             END IF;
    --      DBMS_OUTPUT.put_line (UTL_TCP.get_line (conn, TRUE));
    -- build the start of the mail message ...
             rc := utl_tcp.write_line ( conn, p_datestring );
             rc := utl_tcp.write_line ( conn, 'From: ' || from_name );
             rc := utl_tcp.write_line ( conn, 'Subject: ' || subject );
             rc := utl_tcp.write_line ( conn, 'To: ' || to_name );
             IF cc_name IS NOT NULL
             THEN
                rc := utl_tcp.write_line ( conn, 'Cc: ' || cc_name );
             END IF;
             IF bcc_name IS NOT NULL
             THEN
                rc := utl_tcp.write_line ( conn, 'Bcc: ' || bcc_name );
             END IF;
             rc := utl_tcp.write_line ( conn, 'Mime-Version: 1.0' );
                  -- Set priority:
             --   High      Normal       Low
             --   1     2     3     4     5
             IF ( priority IS NOT NULL )
             THEN
                rc := utl_tcp.write_line ( conn, 'X-Priority: ' || priority );
             END IF;
             rc := utl_tcp.write_line ( conn, 'X-Mailer: ' || mailer_id );
             rc :=
                utl_tcp.write_line
                   ( conn
    ,                'Content-Type: multipart/mixed; boundary="=_mixed 0052287A85256E75_="' );
             rc := utl_tcp.write_line ( conn, '' );
             rc :=
                utl_tcp.write_line
                   ( conn
    ,                'This is a Mime message, which your current mail reader may not' );
             rc :=
                utl_tcp.write_line
                   ( conn
    ,                'understand. Parts of the message will appear as text. If the remainder' );
             rc :=
                utl_tcp.write_line
                   ( conn
    ,                'appears as random characters in the message body, instead of as' );
             rc :=
                utl_tcp.write_line
                   ( conn
    ,                'attachments, then you''ll have to extract these parts and decode them' );
             rc := utl_tcp.write_line ( conn, 'manually.' );
             rc := utl_tcp.write_line ( conn, '' );
             rc := utl_tcp.write_line ( conn, '--=_mixed 0052287A85256E75_=' );
             rc :=
                utl_tcp.write_line ( conn
    ,                                'Content-Type: text/html; charset=8859-1' );
             rc := utl_tcp.write_line ( conn, '' );
             rc := utl_tcp.write_line ( conn, '<html>' );
             rc := utl_tcp.write_line ( conn, '<head>' );
             rc :=
                utl_tcp.write_line
                   ( conn
    ,                '<meta http-equiv="Content-Type" content="text/html;charset=8859-1">' );
             rc := utl_tcp.write_line ( conn, '<title>' );
             rc := utl_tcp.write_line ( conn, subject );
             rc := utl_tcp.write_line ( conn, '</title>' );
             rc := utl_tcp.write_line ( conn, '</head>' );
             rc := utl_tcp.write_line ( conn, '<body>' );
             WHILE pos < msg_length
             LOOP
                rc :=
                   utl_tcp.write_line ( conn
    ,                                   dbms_lob.SUBSTR ( MESSAGE
    ,                                                     offset
    ,                                                     pos ));
                pos := pos + offset;
                offset := LEAST ( bytes_o_data, msg_length - offset );
             END LOOP;
             rc := utl_tcp.write_line ( conn, '<BR><BR>' );
             rc := utl_tcp.write_line ( conn, '</body></html>' );
             rc := utl_tcp.write_line ( conn, '' );
             rc := utl_tcp.write_line ( conn, crlf );
    -- Append the file BLOB  ...
                -- If the filename has been supplied ... it will fail if the BLOB is empty
             IF filename IS NOT NULL
             THEN
                BEGIN
                   -- generate the MIME boundary line ...
                   rc :=
                        utl_tcp.write_line ( conn, '--=_mixed 0052287A85256E75_=' );
                   rc :=
                      utl_tcp.write_line
                              ( conn
    ,                              'Content-Type: application/octet-stream; name="'
                                || filename
                                || '"' );
                   rc :=
                      utl_tcp.write_line
                                  ( conn
    ,                                  'Content-Disposition: attachment; filename="'
                                    || filename
                                    || '"' );
                   rc :=
                      utl_tcp.write_line ( conn
    ,                                      'Content-Transfer-Encoding: base64' );
                   rc := utl_tcp.write_line ( conn, '' );
                   rc := utl_tcp.write_line ( conn, '' );
                   -- and append the file contents to the end of the message ...
                   -- Go get the file and the loop through blob and attach data
                   -- and append the file contents to the end of the message ...
                   attach_base64 ( conn =>                          conn
    ,                              DATA =>                          l_blob );
                EXCEPTION
                   WHEN OTHERS
                   THEN
                      p_output_message :=
                            'Error in attaching file '
                         || filename
                         || ' :: '
                         || SQLCODE
                         || ' - '
                         || SQLERRM;
                      IF DEBUG = 1
                      THEN                                              -- No Output
                         NULL;
                      ELSE                              -- Then DBMS_OUTPUT messages
                         print_output ( p_output_message );
                      END IF;
                      RAISE err_message_send;
                END;
             END IF;
             rc := utl_tcp.write_line ( conn, '' );
             -- append the final boundary line ...
             rc := utl_tcp.write_line ( conn, '' );
             rc := utl_tcp.write_line ( conn, '--=_mixed 0052287A85256E75_=--' );
             rc := utl_tcp.write_line ( conn, '' );
             -- and close the SMTP connection  ...
             rc := utl_tcp.write_line ( conn, '.' );
             ----- EMAIL MESSAGE BODY END
             p_output_message := utl_tcp.get_line ( conn, TRUE );
             IF DEBUG = 1
             THEN                                                       -- No Output
                NULL;
             ELSE                                       -- Then DBMS_OUTPUT messages
                print_output ( p_output_message );
             END IF;
    --      DBMS_OUTPUT.put_line (UTL_TCP.get_line (conn, TRUE));
             rc := utl_tcp.write_line ( conn, 'QUIT' );
             ----- ENDS EMAIL TRANSACTION
             p_output_message := utl_tcp.get_line ( conn, TRUE );
             -- Capture '.' Message sent dialog
             IF DEBUG = 1
             THEN                                                       -- No Output
                NULL;
             ELSE                                       -- Then DBMS_OUTPUT messages
                print_output ( p_output_message );
             END IF;
             BEGIN
                FOR i_idx IN 1 .. 100
                LOOP
                   p_output_message := utl_tcp.get_line ( conn, TRUE );
                   IF DEBUG = 1
                   THEN                                                -- No Output
                      NULL;
                   ELSE                                 -- Then DBMS_OUTPUT messages
                      print_output ( p_output_message );
                   END IF;
                END LOOP;
             EXCEPTION
                WHEN OTHERS
                THEN
                   IF DEBUG = 1
                   THEN                                                -- No Output
                      NULL;
                   ELSE                                 -- Then DBMS_OUTPUT messages
                      print_output ( p_output_message );
                   END IF;
             END;
          END IF;                                               -- err_server_reject
          utl_tcp.close_connection ( conn );        ----- CLOSE SMTP PORT CONNECTION
       EXCEPTION
          WHEN err_message_send
          THEN
             print_output (    CHR ( 10 )
                            || CHR ( 10 )
                            || 'ERROR -'
                            || ' Message was not submitted for delivery' );
             print_output ( ' [FROM_NAME := ' || from_name || '] ' );
             print_output ( ' [TO_NAME := ' || to_name || '] ' );
             print_output ( ' [CC_NAME := ' || cc_name || '] ' );
             print_output ( ' [BCC_NAME := ' || bcc_name || '] ' );
             print_output ( ' [SUBJECT := ' || subject || '] ' );
             print_output ( ' SERVER_MSG := ' || p_output_message );
             utl_tcp.close_connection ( conn );     ----- CLOSE SMTP PORT CONNECTION
          WHEN err_server_reject
          THEN
             print_output (    CHR ( 10 )
                            || CHR ( 10 )
                            || 'ERROR -'
                            || ' Server Rejected Email' );
             print_output ( ' [FROM_NAME := ' || from_name || '] ' );
             print_output ( ' [TO_NAME := ' || to_name || '] ' );
             print_output ( ' [CC_NAME := ' || cc_name || '] ' );
             print_output ( ' [BCC_NAME := ' || bcc_name || '] ' );
             print_output ( ' [SUBJECT := ' || subject || '] ' );
             print_output ( ' SERVER_MSG := ' || p_output_message );
          WHEN OTHERS
          THEN
             print_output (    CHR ( 10 )
                            || CHR ( 10 )
                            || 'ERROR :: '
                            || SQLCODE
                            || ' - '
                            || SQLERRM );
             print_output ( ' [FROM_NAME := ' || from_name || '] ' );
             print_output ( ' [TO_NAME := ' || to_name || '] ' );
             print_output ( ' [CC_NAME := ' || cc_name || '] ' );
             print_output ( ' [BCC_NAME := ' || bcc_name || '] ' );
             print_output ( ' [SUBJECT := ' || subject || '] ' );
             print_output ( ' SERVER_MSG := ' || p_output_message );
       END sendmail;
    END;
    /

    Perhaps your new SMTP server requires a more secure form of authentication than AUTH LOGIN. If you telnet to this new SMTP server on port 25 you should be issue the HELO or EHLO command to find out what AUTH mechanisms the server supports. You could then alter your code to use one of the supported authentication mechanisms.

Maybe you are looking for