为什么在 Java 中实例化 SimpleEmail 类时会收到此异常? [英] Why am I getting this exception when I instantiate a SimpleEmail class in Java?

查看:27
本文介绍了为什么在 Java 中实例化 SimpleEmail 类时会收到此异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的就是用 Java 发送电子邮件.这是我找到的示例:

All I want to do is send an email in Java. Here is the example I found:

import org.apache.commons.mail.SimpleEmail;

public class Email {

    public static void sendMessage(String emailaddress, String subject, String body) {
        try {
            SimpleEmail email = new SimpleEmail();
            email.setHostName("valid ip address here");
            email.addTo(emailaddress);
            email.setFrom("noreply@example.com", "No reply");
            email.setSubject(subject);
            email.setMsg(body);
            email.send();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

我立即在 SimpleEmail email = new SimpleEmail(); 行收到以下异常:

I immediately get the following exception on the SimpleEmail email = new SimpleEmail(); line:

java.lang.ClassNotFoundException: org.apache.commons.mail.SimpleEmail

我的项目中有以下 JAR(使用 Netbeans):commons-email-1.2.jar

I have the following JAR in my project (using Netbeans): commons-email-1.2.jar

我做错了什么?

谢谢.

推荐答案

不知道为什么 SimpleEmail 不起作用.但这确实做到了:

Not sure why SimpleEmail didn't work. But this did:

import javax.mail.*;
  import javax.mail.internet.*;

  import java.util.Properties;

  public class Email {

     public static void sendMessage(String emailaddress, String subject, String body) {
        try {
           Properties props = new Properties();
           props.setProperty("mail.transport.protocol", "smtp");
           props.setProperty("mail.host", "myhost");

           Session mailSession = Session.getDefaultInstance(props, null);
           Transport transport = mailSession.getTransport();

           MimeMessage message = new MimeMessage(mailSession);
           message.setSubject("Testing javamail plain");
           message.setContent("This is a test", "text/plain");
           message.addRecipient(Message.RecipientType.TO, new InternetAddress("test@example.com"));

           transport.connect();
           transport.sendMessage(message,
                   message.getRecipients(Message.RecipientType.TO));
           transport.close();
        } catch (Exception ex) {
           ex.printStackTrace();
        }
     }
  }

感谢您的建议.

这篇关于为什么在 Java 中实例化 SimpleEmail 类时会收到此异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆