javajakarta-mailnosuchproviderexception

How to correct Invalid Protocol: null sending mail using javax.mail


i'm trying to send mail in this way:

Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "out.alice.it");
props.setProperty("mail.user", "mymail@domain.it");
props.setProperty("mail.password", "*****");
Session mailSession = Session.getDefaultInstance(props, null);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress("Host", "Name"));

On the row Transport transport... i retrieve this error:

javax.mail.NoSuchProviderException: Invalid protocol: null
    at javax.mail.Session.getProvider(Session.java:440)
    at javax.mail.Session.getTransport(Session.java:659)
    at javax.mail.Session.getTransport(Session.java:640)
    at javax.mail.Session.getTransport(Session.java:626)
    at Mail.sendMail(Mail.java:151)

How can i resolve? Can someone help me? Thanks!! :)

EDIT:

If i create a main and launch that method to send mail, it works good! My problem borns after i read mail into mail folder:

Properties properties = System.getProperties();  
properties.setProperty("mail.store.protocol", "imap");  
Session session = Session.getDefaultInstance(properties, null);
Store store = session.getStore("pop3");
store.connect("pop3.domain.it", "mail@domain.it", "****");  
Folder inbox = store.getFolder("inbox");  
FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.search(ft);
for(Message message:messages) {
   if(message.getFrom()[0].toString().equals("aMail")){
      sendMail(message.getFrom()[0].toString());//Error!
   }
}

I Thought the exception borns cause i've opened store to get inbox mail so i edit in this way:

ArrayList<String> reply = new ArrayList<String();
for(Message message:messages) {
    if(message.getFrom()[0].toString().equals("aMail")){
        reply.add(message.getFrom()[0].toString());
    }
}
store.close();
for(String mail : reply){
   sendMail(mail); // ERROR AGAIN!
}

very strange....

SOLVED IN THIS WAY:

i modified this row

Session mailSession = Session.getDefaultInstance(props, null);

to

Session mailSession = Session.getInstance(props);

Solution

  • you might try another way:

    Properties props = new Properties();
    props.setProperty("mail.transport.protocol", "smtp");
    props.setProperty("mail.smtp.host", "out.alice.it");
    props.setProperty("mail.smtp.auth", "true");
    final PasswordAuthentication auth = new PasswordAuthentication(smtpUser, stmpPassword);
    Session mailSession = Session.getDefaultInstance(props, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() { return auth; }
    });
    MimeMessage message = ....;
    // compose the message
    Transport.send(message);