如何更正无效协议:null使用javax.mail发送邮件
我正试图以这种方式发送邮件:
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 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);
你可以尝试另一种方式:
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);
我得到了同样的错误,我的问题是我忘了包括:
props.put("mail.transport.protocol", "smtp");