4

我正在尝试以这种方式发送邮件:

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

Transport transport...我检索此错误的行上:

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)

我该如何解决?有人能帮我吗?谢谢!!:)

编辑:

如果我创建一个 main 并启动该方法来发送邮件,它工作得很好!在我将邮件读入邮件文件夹后,我的问题就出现了:

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!
   }
}

我认为异常的原因是我已经打开商店以获取收件箱邮件,所以我以这种方式编辑:

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!
}

很奇怪....

以这种方式解决:

我修改了这一行

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

Session mailSession = Session.getInstance(props);
4

2 回答 2

4

你可以尝试另一种方式:

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);
于 2012-06-29T17:16:03.177 回答
3

我遇到了同样的错误,我的问题是我忘了包括:

props.put("mail.transport.protocol", "smtp");
于 2017-02-28T00:09:00.937 回答