Почтовый класс скинуть ClassFormatError: для javax/mail/Authenticator
Добро пожаловать,
Я написал пример простого тестового класса JavaMail API - отправка электронной почты - от mkyong работает отлично, но если я создаю отдельный класс без основного метода, как это:
import com.sedzisz.papersoccer.PaperSoccer;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
public class SendMail {
private static final Logger LOG = Logger.getLogger(SendMail.class.getName());
private final Level logLevel;
private String propertyFileName;
private final Properties props;
public String getMessageText() {
return messageText;
}
public void setMessageText(String messageText) {
this.messageText = messageText;
}
public String getRecipientEmailAddress() {
return recipientEmailAddress;
}
public void setRecipientEmailAddress(String recipientEmailAddress) {
this.recipientEmailAddress = recipientEmailAddress;
}
private String messageText;
private String recipientEmailAddress;
public SendMail(String propertyFileName) {
this.logLevel = Level.INFO;
propertyFileName = "gmail.properties";
if (propertyFileName != null) {
this.propertyFileName = propertyFileName;
}
LOG.log(Level.INFO, "Set property file name [{0}]", propertyFileName);
LOG.setLevel(logLevel);
props = new Properties();
loadProperties(propertyFileName);
}
public boolean sendMessageTo() throws FileNotFoundException {
if (props.isEmpty()) {
throw new FileNotFoundException("Can't load propertis for mail connections");
} else {
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
String userName = props.getProperty("username");
String password = props.getProperty("password");
LOG.log(logLevel, "User name [{0}], password [{1}]", new Object[]{userName, password});
return new PasswordAuthentication(userName, password);
}
});
// Message message = new MimeMessage(session);
//
boolean succes = false;
// try {
// message.setFrom(new InternetAddress(props.getProperty("username")));
// message.setRecipients(Message.RecipientType.TO,
// InternetAddress.parse(recipientEmailAddress));
// message.setSubject("Testing mail");
// message.setText("Weclome companion!,\n" + messageText
// + "\n You wonn premmum code for redtube.com ;)");
// Transport.send(message);
// succes = true;
// } catch (AddressException ax) {
// LOG.info("Ble ble ble coś tam żle!!!");
// } catch (MessagingException me) {
// LOG.info("Jak wyżej tylko chodzi o maila");
// } finally {
return succes;
// }
}
}
private void loadProperties(String fileName) {
ClassLoader loader = PaperSoccer.class.getClassLoader();
System.setProperty("file.encoding", "UTF-8");
LOG.log(Level.INFO, "File encoding [{0}]", System.getProperty("file.encoding"));
LOG.log(Level.INFO, "File name [{0}]", fileName);
InputStream is;
try {
loader.getResource(fileName);
LOG.log(Level.INFO, "Path to file [{0}]", loader.getResource(fileName));
is = loader.getResourceAsStream(fileName);
props.load(is);
is.close();
if (logLevel == Level.WARNING) {
for (String key : props.stringPropertyNames()) {
String value = props.getProperty(key);
LOG.log(Level.WARNING, "{0}= [{1}]", new Object[]{key, value});
}
}
if (props.size() > 0) {
LOG.log(logLevel, "Properties have [{0}] parameters", props.size());
}
} catch (FileNotFoundException e) {
LOG.log(Level.INFO, "File [{0}] not found", fileName);
} catch (IOException e) {
LOG.log(Level.INFO, "Cannt read file [{0}]", fileName);
}
}
}
Maven зависимость:
<!-- Java Mail -->
<!--
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
<type>jar</type>
</dependency>
-->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
<type>jar</type>
</dependency>
<!-- Java Mail -->
Я получил эту ошибку:
java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/mail/Authenticator
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:792)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at com.sedzisz.papersoccer.activationMail.SendMailTest.hello(SendMailTest.java:44)
Что не так с моим кодом?
Я делаю что-то вроде этого:
private class MAuthenticator extends javax.mail.Authenticator {
public MAuthenticator() {
super();
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
String userName = props.getProperty("username");
String password = props.getProperty("password");
LOG.log(logLevel, "User name [{0}], password [{1}]", new Object[]{userName, password});
return new PasswordAuthentication(userName, password);
}
}
Но я получаю эту же ошибку.
Я делаю это в трее:
public boolean sendMessageTo(){
Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
};
Session session = Session.getInstance(props, auth);
}
нет результатов, простой модульный тест, как:
@Test
public void testSendMail(){
SendMail sm = new SendMail();
}
бросай всегда исключение
1 ответ
Моя вина, что я не дал вам всю информацию о проекте, мой pom немного жирнее, и у меня есть зависимость от javaee-web-api
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
я просто перенесу это
<!-- Java Mail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
<type>jar</type>
</dependency>
<!-- Java Mail -->
выше javaee-web-api и проблема исчезла.... almoste
public boolean sendMessageTo() {
Authenticator auth = new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
LOG.info("Create authenticator class and return PasswordAuthenticator");
return new PasswordAuthentication(props.getProperty("username"), props.getProperty("username"));
}
};
Session session = Session.getInstance(props, auth);
Message message = new MimeMessage(session);
boolean succes = false;
try {
message.setFrom(new InternetAddress(props.getProperty("username")));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(recipientEmailAddress));
message.setSubject("Testing mail");
message.setText("Weclome companion!,\n" + messageText
+ "\n You wonn premmum code for redtube.com ;)");
Transport.send(message);
succes = true;
} catch (AddressException ax) {
System.err.println(ax);
} catch (MessagingException me) {
System.err.println(me);
} finally {
return succes;
}
}
Теперь у меня другая проблема
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.sedzisz.papersoccer.activationMail.SendMailTest
gru 27, 2013 11:42:22 AM com.sedzisz.papersoccer.activationMail.SendMail <init>
INFO: Set property file name [gmail.properties]
gru 27, 2013 11:42:22 AM com.sedzisz.papersoccer.activationMail.SendMail loadProperties
INFO: File encoding [UTF-8]
gru 27, 2013 11:42:22 AM com.sedzisz.papersoccer.activationMail.SendMail loadProperties
INFO: File name [gmail.properties]
gru 27, 2013 11:42:22 AM com.sedzisz.papersoccer.activationMail.SendMail loadProperties
INFO: Path to file [file:/D:/source/java/NetBeansProjects/PaperSoccer/target/classes/gmail.properties]
gru 27, 2013 11:42:22 AM com.sedzisz.papersoccer.activationMail.SendMail$1 getPasswordAuthentication
INFO: Create authenticator class and return PasswordAuthenticator
javax.mail.AuthenticationFailedException
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 2.042 sec <<< FAILURE! - in com.sedzisz.papersoccer.activationMail.SendMailTest
hello(com.sedzisz.papersoccer.activationMail.SendMailTest) Time elapsed: 1.996 sec <<< FAILURE!
Это должно быть легко решить!
Благодарю вас:)
return new PasswordAuthentication(props.getProperty("username"), props.getProperty("username"));
Вторым параметром должен быть пароль, а не имя пользователя! все работает отлично! Еще раз спасибо за ваше время;)