views:

366

answers:

1

So, my problem is the following: I have a mail client that I wrote in Java and I cannot send mails through SMTP after I check my mails with POP3.

The exception I caught says that the transport protocol = null.

The code is working fine, because I have no issue before POP3 connection. I am sure I close that connection and they are all private functions, so the variables are not effective on each other.

Hope I told everything.

Thanks for any idea.

The codes:

pop3 connection

  // Connect to the POP3 server
  Session session = Session.getDefaultInstance(props, null);
  Store store = session.getStore("pop3");
  store.connect(host, username, password);

  // Open the folder
  Folder inbox = store.getFolder("INBOX");

  inbox.open(Folder.READ_ONLY);

  // Get the messages from the server
  Message[] messages = inbox.getMessages();


  fromMailAddress.setText(userAccount);

  // Close the connection
  // but don't remove the messages from the server
  inbox.close(false);
  store.close();
  props.clear();
    }
catch (Exception ex) {
     JOptionPane.showMessageDialog(null,"user input error", "error", JOptionPane.ERROR_MESSAGE);


    }

smtp - mail sending

    Properties property = new Properties();
    property.setProperty("mail.transport.protocol", "smtp");
    property.setProperty("mail.host", "mymailserver");
    property.setProperty("mail.user", "myusername");
    property.setProperty("mail.password", "mypassword");
    Session mailSession = Session.getDefaultInstance(property, null);
    mailSession.setDebug(true);
try{
    Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject("HTML  mail with images");
    message.setFrom(new InternetAddress("[email protected]"));
    message.setContent("<h1>Hello world</h1>", "text/html");
    message.addRecipient(Message.RecipientType.TO,
    new InternetAddress("[email protected]"));

    transport.connect();
    transport.sendMessage(message,
        message.getRecipients(Message.RecipientType.TO));
    transport.close();
    property.clear();
    }
    catch(Exception ex)
    {

            JOptionPane.showMessageDialog(null,"e-mail sending failed", "Error", JOptionPane.ERROR_MESSAGE);
 }
+1  A: 

Your pop and smtp modules not independent: they are sharing the default session. Instead of relying on javamail's default session (Session.getDefaultInstance), you'd be better off creating your own sessions, one for pop and one for smtp.

jdigital
i wonder if you could give me an example of creating my own session, it'd be very helpful, thank you.
Hectai
Try Session.getInstance(property). You'll want to hold onto the the session (rather than calling getInstance each time).
jdigital
it solved my problems, thank you very much
Hectai