开发者

Javamail problem: cannot send mails through SMTP after checking mails with POP3

开发者 https://www.devze.com 2022-12-14 09:33 出处:网络
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.

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("myaddress@gmail.com"));
    message.setContent("<h1>Hello world</h1>", "text/ht开发者_运维问答ml");
    message.addRecipient(Message.RecipientType.TO,
    new InternetAddress("xyz@gmail.com"));

    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);
    }


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消