Error in sending mail 2nd time, Where is the fault- Help Please

Hi friends,
I had written a program to send mail. Everything is fine, when i send first time. But if I try to send mail 2nd time, It gives the error:
Exception in Connect: IOException while sending message
Here is the complete code what i had written, It successfully connects using t.connect();
the problem in t.send();
output on JBoss Console is :
Inside Action
After Transport t = session.getTransport(protocol)
before t.connect()
after t.connect()
Exception in Connect IOException while sending message
import java.io.*;
import java.util.*;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
public class MsgSend extends Action {
     @Override
     public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request
               , HttpServletResponse response) throws Exception {
          response.setContentType("text/xml");
          PrintWriter out = response.getWriter();
          System.out.println("Inside Action");
            String to = request.getParameter("to");
         String bcc = request.getParameter("bcc");
         String cc = request.getParameter("cc");
         String subject = request.getParameter("sub");
         String user = request.getParameter("user");
         //String password = request.getParameter("pass");
         String message = request.getParameter("message");
         String from = user + "@domainname.com" ;
         /*Properties props = System.getProperties();
         props.put("mail.smtp.host", "smtp.vsginc.com");
          MailBean  bean = MailBean.getInstance();          
          Session session = bean.getSession();          
          String protocol = "smtp";
          Transport t = session.getTransport(protocol);
          System.out.println("After Transport t =              session.getTransport(protocol)");
         MimeMessage msg = new MimeMessage(session);
         msg.setFrom(new InternetAddress(from));
         InternetAddress[] address = {new InternetAddress(to)};
         msg.setRecipients(Message.RecipientType.TO, address);
         if(cc != null ){
               InternetAddress ccAddr[]  = InternetAddress.parse(cc);
               msg.setRecipients(Message.RecipientType.CC, ccAddr);
          if(bcc != null){
               InternetAddress bccAddr[] = InternetAddress.parse(bcc);
               msg.setRecipients(Message.RecipientType.BCC,bccAddr);
         msg.setSubject(subject);
         // create and fill the first message part
         MimeBodyPart messageBodyPart = new MimeBodyPart();
         messageBodyPart.setText(message);
         Multipart multipart = new MimeMultipart();
         multipart.addBodyPart(messageBodyPart);
         Attachment attachment = Attachment.getInstance();
         ArrayList<String> fileList = attachment.getFileNames();
         String parentFolder = null;
         for(String path:fileList){
              File attachmentFile = new File(path);
              messageBodyPart = new MimeBodyPart();
              DataSource source = new FileDataSource(attachmentFile);
              messageBodyPart.setDataHandler(new DataHandler(source));
              messageBodyPart.setFileName(attachmentFile.getName());
              multipart.addBodyPart(messageBodyPart);
              parentFolder = attachmentFile.getParent();
         // add the Multipart to the message
         msg.setContent(multipart);
         // set the Date: header
         msg.setSentDate(new Date());        
         try {
              System.out.println("before t.connect()");
               t.connect(bean.getSmtpServer(),bean.getUsername() ,bean.getPassword());
               System.out.println("after t.connect()");
               //Error is coming here in this Line.
               t.sendMessage(msg, msg.getAllRecipients());
               * System.gc(); will relese the fileHandles, if some resource
               * still holds it.               
               System.out.println("before System.gc()");
               System.gc();
               * Deleting All the Files from Attachment Folders.
              System.out.println("before attachmentFolder");
              File attachmentFolder = new File(parentFolder);
              System.out.println("Attachment Folder Name is : "+attachmentFolder.getAbsolutePath());
              if(attachmentFolder.isDirectory()){
                   File[] files = attachmentFolder.listFiles();
                   System.out.println("No of Files For Attachments are: "+files.length);
                   boolean deleteResult = false;
                   for(int i=0; i<files.length; i++ ){
                        deleteResult = files.delete();
                    System.out.println(files[i].getName() + " Delete Staus is :"+ deleteResult);
          System.out.println("All attachments Deleted");
          out.print("<result>Mail has been sent successfully</result>");
          } catch (Exception e) {
               out.print("<result>Mail sending failed</result>");
               System.out.println("Exception in Connect "+e.getMessage());
          }finally{
               t.close();               
          return null;
Problem only comes, when i send 2nd time or more. What is the problem? Please help me out.
Thanks for your response in advance. One more thing, Whether to send a mail & receive a mail, we need to create different sessions. one for sending & one for receiving mails.
Message was edited by:
Ashish.Mishra16

I don't see anything obviously wrong in your code. Try adding
session.setDebug(true);
You can use the same Session for sending and for reading.
A Session just encapsulates your configuration parameters,
so as long as they're the same for both usages, one Session
is fine.

Similar Messages

  • Error in sending mail using ssl server

    Hi All
    Please help in resolving the below issue i am getting the following error while sending mail. I am using the IMAP server and it is ssl configured.
    DEBUG: setDebug: JavaMail version 1.4ea
    DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc]
    DEBUG SMTP: useEhlo true, useAuth false
    DEBUG SMTP: trying to connect to host "mail.test.com", port 465, isSSL true
    DEBUG SMTP: exception reading response: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: subject/issuer name chaining check failed
    javax.mail.MessagingException: Exception reading response;
      nested exception is:
         javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: subject/issuer name chaining check failed
         at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1462)
         at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1260)
         at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
         at javax.mail.Service.connect(Service.java:275)
         at com.test.test.JavaMailApp2.main(JavaMailApp2.java:59)
    Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: subject/issuer name chaining check failed
         at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source)
         at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(Unknown Source)
         at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
         at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
         at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(Unknown Source)
         at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(Unknown Source)
         at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Unknown Source)
         at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Unknown Source)
         at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
         at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
         at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readDataRecord(Unknown Source)
         at com.sun.net.ssl.internal.ssl.AppInputStream.read(Unknown Source)
         at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:97)
         at java.io.BufferedInputStream.fill(Unknown Source)
         at java.io.BufferedInputStream.read(Unknown Source)
         at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:75)
         at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1440)
         ... 4 more
    Caused by: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: subject/issuer name chaining check failed
         at sun.security.validator.PKIXValidator.doValidate(Unknown Source)
         at sun.security.validator.PKIXValidator.doValidate(Unknown Source)
         at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
         at sun.security.validator.Validator.validate(Unknown Source)
         at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(Unknown Source)
         at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
         at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
         ... 17 more
    Caused by: java.security.cert.CertPathValidatorException: subject/issuer name chaining check failed
         at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(Unknown Source)
         at sun.security.provider.certpath.PKIXCertPathValidator.doValidate(Unknown Source)
         at sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(Unknown Source)
         at java.security.cert.CertPathValidator.validate(Unknown Source)
         ... 24 moreBelow is the source code of the program.
    package com.test.test;
    import java.security.Security;
    import java.util.Properties;
    import javax.mail.Authenticator;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.NoSuchProviderException;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.AddressException;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    public class JavaMailApp {
         public static void main( String[] args )
              String d_email = "[email protected]";
              String d_uname = "ots.support";
              String d_password = "password";
              String d_host = "mail.test.com";
              String d_port  = "465"; //465,587
              String m_to = "[email protected]";
              String m_subject = "Testing";
              String m_text = "Hey, this is the testing email.";
              Properties props = new Properties();
              props.put("mail.smtp.user", d_email);
              props.put("mail.smtp.host", d_host);
              props.put("mail.smtp.port", d_port);
              props.put("mail.smtp.starttls.enable","true");
              props.put("mail.smtp.debug", "true");
              props.put("mail.smtp.auth", "true");
              props.put("mail.smtp.socketFactory.port", d_port);
              props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
              props.put("mail.smtp.socketFactory.fallback", "false");
              SMTPAuthenticator auth = new SMTPAuthenticator();
              Session session = Session.getInstance(props, auth);
              session.setDebug(true);
              MimeMessage msg = new MimeMessage(session);
              try {
                   msg.setText(m_text);
                   msg.setSubject(m_subject);
                   msg.setFrom(new InternetAddress(d_email));
                   msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
                   Transport transport = session.getTransport("smtps");
                   transport.connect(d_host, 465, d_uname, d_password);
                   transport.sendMessage(msg, msg.getAllRecipients());
                   transport.close();
              } catch (MessagingException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    public class SMTPAuthenticator extends Authenticator{
         public PasswordAuthentication getPasswordAuthentication()
            return new PasswordAuthentication("[email protected]", "password");
    }I have also added the certificate to my keystore using the following command and still i am facing this issue.
    keytool -import -trustcacerts -alias root -file mail_test_com.crt -keystore keystore.jks
    Add to fierof2's Reputation

    this is where i created the keystore.jks file
    I navigated to the location C:\Program Files\Java\jdk1.6.0_13\bin in command prompt and typed the following command to create the keystore
    keytool -import -trustcacerts -alias root -file mail_test_com.crt -keystore keystore.jksI was asked to set the password for keystore and then i was asked the question "Trust this certificate? [no]:" for which i gave yes.
    If this is not the right place to create the keystore.jks can you please tell me what is correct location to create the keystore file.

  • "This message cannot be sent at this time."  I have been getting this pop-up for 3 days when trying to send out mail.  I don't know what to do!  I cannot send mail from this account on any ISP. Please help!

    "This message cannot be sent at this time."  I have been getting this pop-up for 3 days when trying to send out mail.  I don't know what to do!  I cannot send mail from this account on any ISP. Please help!

    lots of people seem to be havgin a problem sending email from iCloud webmail.
    does your email address have uppercase characters in it?
    if so, try creating an alias in lowercase (go to preferences in iCloud webmail and select 'accounts') and see if email sends okay from that

  • Error while sending mail from SAP

    Hello All,
    Recently we are facing an error while sending mail from SAP. When we try to compose a message ,it is moving to a dump error RAISE_EXCEPTION.
    The details from ST22,
    Short text
        Exception condition "FOLDER_NOT_EXIST" raised.
    Error analysis
        A RAISE statement in the program "SA
        condition "FOLDER_NOT_EXIST".
        Since the exception was not intercep
        program, processing was terminated.
    Kindly suggest..
    Thank You,
    Regards,
    Hasan

    Hello Priyanka,
    Actually, I performed the following two steps in order to solve the issue:
    - In transaction SICF, the node for SAPConnect must be active. In our system, this node was in inactive state. Hence I activated it.
    - Then In transaction SCOT-> Settings menu--> default domain should be 'xyz.com' if the email addresses in your company are maintained with a suffix  xyz.com.
    But for me the problem didnt get solved here..
    The problem that i am facing now is that if in my user profile, I have the email address maintained, then i get an error saying 'Sender address rejected'. However, if i goto transaction SU01 and clear the email id, the mail is successfully sent to outer world.
    You can try the above mentioned two steps using SICF and SCOT. If the problem does not get solved then try clearing the mail id in ur user profile.
    Hope this helps. If you find an answer to the problem of the mail id getting cleared, then please let me know..
    Regards,
    Himanshu

  • Windows live mail having problum after joining in domain examples incoming is good but sent or outgoing is not there and also send mails are not exporting at the time of live mail exporting time?

    windows live mail having problem after joining in domain examples incoming is good but sent or outgoing is not there and also send mails are not exporting at the time of live mail exporting time?

    This is not usually related to AD issues, but it may be more of a DNS issue. I posted a request in your other thread to post an unedited ipconfig /all of the DC and of the client.
    This may help use diagnose this issue and your other thread's printer issues.
    Thank you,
    Ace Fekay
    MVP, MCT, MCSE 2012, MCITP EA & MCTS Windows 2008/R2, Exchange 2013, 2010 EA & 2007, MCSE & MCSA 2003/2000, MCSA Messaging 2003
    Microsoft Certified Trainer
    Microsoft MVP - Directory Services
    Complete List of Technical Blogs: http://www.delawarecountycomputerconsulting.com/technicalblogs.php
    This posting is provided AS-IS with no warranties or guarantees and confers no rights.

  • An error occurred sending mail: The mail server sent an incorrect greeting: * OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE STARTTLS AUTH

    Hi, I am receiving emails but whenever I try and send I get the following message:
    unable to send emails An error occurred sending mail: The mail server sent an incorrect greeting: * OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE STARTTLS AUTH=PLAIN AUTH=LOGIN] Dovecot ready..

    What are your settings in Tools(or AppMenu/Options)/Account Settings/Outgoing Server (SMTP)? The error message suggests you must have STARTTLS connection security and normal password authentication:
    https://getsatisfaction.com/mozilla_messaging/topics/mail_preferences-t1xeq

  • MFMessageErrorDomain error 1035 sending mail

    I've just upgraded my second tiger box to leopard.
    Now I can't send mail - it just gives:
    Operation could not be completed. (MFMessageErrorDomain error 1035.)
    Now. The server runs courier imap(s)/pop(s) with a self-cert certificate and smtp (exim4) again with a self-cert certificate (different certificates).
    Under tiger - I had both certificates in the X509Anchors keychain.
    So - to leopard. Note - this is working just fine on the first box I upgraded (mac mini).
    When first browsing the imap server mail says "untrusted certificate". I say always trust, and give an admin user/pass combo. This inserts the certificate into the System keychain.
    But sending via SMTP (start TLS) just gives the 1035 MFMessageErrorDomain error.
    I've tried grabbing the SMTP certificate file instead from my mac mini system keychain (also leopard and happily able to send mail) and importing it to the system keychain. No dice. Mail.app just throws this same error.
    I'm a little lost as to why - and I can't figure out what I have to do to get mail working again.

    Just spotted the following in the console log
    Dec 2 00:02:03 slippen Keychain Access[2720]: Exception raised during start of kcproxy: Couldn't register server "com.apple.KeychainProxyServer" on this host.
    Dec 2 00:02:03 slippen Keychain Access[2720]: Couldn't register server "com.apple.KeychainProxyServer" on this host.
    Again and again.
    Googling isn't showing me much on that one.

  • Urgent:-REP-50152: Error while sending mail

    hi
    i am using reports10g. i have called a report from a form and destype=mail.
    i have already mention the smtp server name in conf. file but still receiving this error
    REP-50152: Error while sending mail - Sending failed; nested exception is: javax.mail.SendFailedException: Invalid Addresses; nested exception is: javax.mail.SendFailedException: 550 5.7.1 Unable to relay for [email protected]
    thanks

    Your smtp server forbids relaying, which is very common. Often a smtp server is configured to send only mails within the same domain without authentication. Otherwise, you need a username and password for the smtp server. I'm not sure if you can configure Reports to send mail through an authenticated server.

  • Terminated with error: REP-50152:Error while sending mail

    Hi
    Gets this error while sending report mails to external email id's
    Terminated with error: REP-50152: Error while sending mail - Sending failed; nested exception is: javax.mail.SendFailedException: Invalid Addresses; nested exception is: javax.mail.SendFailedException: 550 5.7.1 Unable to relay for [email protected]
    Any setting to be done in report config file?
    thanks
    MG

    It should be like this
    <pluginParam name="mailServer">%MAILSERVER_NAME%</pluginParam>
    Specify the name of your mail server in the place of %MAILSERVER_NAME% above
    Also make sure that this is not commented out.
    Thanks,

  • TS3899 How do I change the address that my iphone sends when i send mail.  I have deleted the account but it still shows up as the account that will be replyed to if people hit reply.

    How do I change the address that my iphone sends when i send mail.  I have deleted the account but it still shows up as the account that will be replyed to if people hit reply.

    Hey There I didn't need to change it as it shows my correct name in my icloud account. The problem is on my Mac where it still shows my Full name as my partners name.
    For eg. if I send an email from "Mail" on mac and I use my icloud account then the name that shows up is my partners name when the email is received. If I send an email from the Icloud Mail box that I log into on my browser then the name that shows up when the email is received is my name which is correct.
    When I go into preferences in "Mail" on my Mac to change my name, the name is ghosted out and doesn't allow me to change it ! ? It is here that it still show my partners name ?

  • I want to copy and past 58 links from my IE favorites into the bookmarks toolbar...not one at a time. where's the folder i can copy these too?

    i want to copy and past 58 links from my IE favorites into the bookmarks toolbar...not one at a time. where's the folder i can copy these too?
    == This happened ==
    Not sure how often
    == i want to copy and past 58 links from my IE favorites into the bookmarks toolbar...not one at a time. where's the folder i can copy these too?

    Firefox doesn't store the bookmarks as separate files in a folder, but uses a sqlite database file with the name places.sqlite.
    You will have to export those favorites in IE to an HTML file and import that file in Firefox.
    Bookmarks > Organize Bookmarks > Import & Backup > Import HTML : "From File"
    See http://kb.mozillazine.org/Backing_up_and_restoring_bookmarks_-_Firefox

  • When I try to install Itunes, I get this error: (translated from Norwegian) There was a network error while trying to read from the file: C: \ windows \ installer \ iTunes.msi I have tried many times to reinstall, but nothing helps, please help me.

    When I try to install Itunes, I get this error: (translated from Norwegian) There was a network error while trying to read from the file: C: \ windows \ installer \ iTunes.msi I have tried many times to reinstall, but nothing helps, please help me.

    (1) Download the Windows Installer CleanUp utility installer file (msicuu2.exe) from the following Major Geeks page (use one of the links under the "DOWNLOAD LOCATIONS" thingy on the Major Geeks page):
    http://majorgeeks.com/download.php?det=4459
    (2) Doubleclick the msicuu2.exe file and follow the prompts to install the Windows Installer CleanUp utility. (If you're on a Windows Vista or Windows 7 system and you get a Code 800A0046 error message when doubleclicking the msicuu2.exe file, try instead right-clicking on the msicuu2.exe file and selecting "Run as administrator".)
    (3) In your Start menu click All Programs and then click Windows Install Clean Up. The Windows Installer CleanUp utility window appears, listing software that is currently installed on your computer.
    (4) In the list of programs that appears in CleanUp, select any iTunes entries and click "Remove", as per the following screenshot:
    (5) Quit out of CleanUp, restart the PC and try another iTunes install. Does it go through properly this time?

  • Can not send mail from PR Workflow to the approver

    Dear all,
    I have issues about send mail from PR Workflow to the approver.
    Now when user create PR and the corresponding user can receive the workflow items in SBWP.
    But no email from the user to approver.
    If I assign authorization SAP_ALL to the user that create PR. The approver can recieve the workflow item PR in SBWP and email to their mail
    Can you tell me about the authorization that can allow the user to send the workflow item PR in SBWP and email to the approver?
    Now user can send mail to external and internal mail and I also configured the mail server in SCOT and can successfully send a mail to users in SO01 by manually creating a message.
    Now the approver not receive any email but can receive a workflow item in SBWP
    Regards,
    Pannee

    Dear all,
    Thank you for all suppport, Now I can solve issues.
    Regards,
    Pannee

  • APPLE TECH TEAM SUGGESTED TO REPLACE MY MACBOOK PRO'S LOGIC BOARD FOR 2ND TIME?All the funtionality and applications is working fine but my screen backlight is off.If i expose it to direct sunlight , i can see what is running on my MAC(out of warranty)

    APPLE TECH TEAM SUGGESTED TO REPLACE MY MACBOOK PRO'S LOGIC BOARD FOR 2ND TIME?All the funtionality and applications is working fine but my screen backlight is off.If i expose it to direct sunlight , i can see what is running on my MAC(out of warranty)

    likely display inverter board.
    did you get your inverter board replaced already?
    Did you have a question?
    If the diagnostic in shop indicates same, thats 1000X better than anyone can do online in "diagnosis" (not really genuine diagnosis of course)

  • In my ipad email address which I am using for sending mail is appearing differently in the receipents mail box ! how to resolve that

    in my ipad email address which I am using for sending mail is appearing differently in the receipents mail box ! how to resolve that

    while sending a email in my ipad it is showing the correct email address([email protected]) in the ""from"" field but in receipients inbox ""from"" field it is showing another email id ([email protected])

Maybe you are looking for

  • Table is not in the same position form 1 page to next

    Hi, Following my earlier posts regarding my website and the lack of text. I thought if I created a new index page with text and and enter site button this would go some way to sorting out the problem. The problem now is that the indes page table is n

  • ToS Preservation with egress remarking on inner packet

    Hi, I am using DMVPN/IPSEC/VRFs. On the egress of the DMVPN/VRF tunnel interfaces, I have applied a Service Policy to remark traffic. Hence the remarking occurs on the inner packet header. Assuming qos-preclassify is NOT enabled. Does anyone know how

  • Icon composer, can make them, can't use them from get info, how?

    Hi, I can make icons in Icon Composer, but when I try to retrieve and use them from the "get info" window there is only a generic ICNS icon available at the top, although the icon I made shows in the preview pane at the bottom. How can I retrieve the

  • Lost all itunes playlists when I reset my apple ID username

    I changed my Apple ID username and now all of my iTunes playlists are gone from my iPhone 5C, however all of my music is still there.  When I log-in to iTunes on my iMac all of my music and playlists are still available.  Why are my playlists gone fr

  • Airplay doesn't work anymore on my iPhone 6 after iOS 8.2 upgrade

    Hello, I'm using Airport Express (2nd generation) for streaming music on my stereo from 2 iPhones: one 5 and one 6. Since I upgraded my iPhone 6 to iOS8.2, Airplay is not working anymore on this phone: Airplay icon is visible and actionnable, but it