java - 邮件类抛出 ClassFormatError : for javax/mail/Authenticator

标签 java jakarta-mail

欢迎,
我写了简单的测试类形式示例a JavaMail API – Sending email - by 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();
    }

总是抛出异常

最佳答案

我的错,我没有向您提供有关项目的所有信息,我的 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并且问题消失了....几乎

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

第二个参数应该是密码而不是用户名!一切正常!再次感谢您抽出时间;)

关于java - 邮件类抛出 ClassFormatError : for javax/mail/Authenticator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20785818/

相关文章:

java - 线程安全与否?从并行流更新非线程安全映射

java - 将 Spring Boot 1.4.4 升级到 1.5.4 - NoClassDefFoundError : ServletRegistrationBean

java - 运行 spring 测试时加载类路径资源时出现 FileNotFoundException

java - 发送邮件时是否需要 TLS 身份验证凭据

Java/JavaMail : Null pointer exception when trying to create a folder to fetch E-Mails (GMAIL/POP3)

java - Singleton 类中的邮件 session

java - 带有 PGPoolingDataSource 的数据库池?

Java for 循环执行了两次

JavaMail 在属性中设置域

java - 如何通过没有列表的电子邮件地址获取邮件主机名、协议(protocol)、端口和加密方法?