繁体   English   中英

如何在Netbeans(Java)中正确使用库?

[英]How to use libraries correctly in Netbeans (Java)?

这个问题是关于用Java编程时如何处理Netbeans中的库的。

我有一个Java项目,我们称之为ABC。 它的活动之一是发送电子邮件。 我的其他一些Java项目也发送电子邮件,因此我决定创建一个单独的Java项目来发送消息。 该项目称为SendEmail。 SendEmail使用外部jar文件(javax.mail。*)。 通过转到SendEmail的项目属性->库->添加JAR,可以包含这些文件。 测试SendEmail可以正常工作:调用其方法sendMail(title,contents)时,我是否收到发送的电子邮件。

Project ABC使用SendEmail,因此我已将其添加到ABC的库中:project Properties-> Libraries-> Add Project。 ABC可以编译并正常运行,直到到达要发送电子邮件的位置:它崩溃了。

private void informUser(){
//create message title
//create message contents
SendEmail email = new SendEmail();
email.sendMail(title, contents); // <- it crashes here
}

错误信息指出它找不到Authenticator类。 此类在SendEmail的库中包含的外部jar文件中。 我只能通过将外部jar文件包含到ABC的库中来避免发生崩溃。 这是我没想到的必要。 ABC不使用这些外部jar文件,仅使用SendEmail。

我的问题:我做错了吗? 我以为ABC不在使用这些外部jar,因此它们不必位于ABC的库中。

在您的代码中,没有身份验证器部分。 此代码只能使用gmail电子邮件,您可以更改smtp服务器选项。 我的代码:

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class GmailSender extends javax.mail.Authenticator {

    private String user;
    private String password;
    private Session session;

    static {
        Security.addProvider(new JSSEProvider());
    }

    public GmailSender(String user, String password) {
        this.user = user;
        this.password = password;

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.quitwait", "false");

        session = Session.getDefaultInstance(props, this);
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, password);
    }

    public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {
        try {
            MimeMessage message = new MimeMessage(session);
            DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
            message.setSender(new InternetAddress(sender));
            message.setSubject(subject);
            message.setDataHandler(handler);
            if (recipients.indexOf(',') > 0)
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
            else
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
            Transport.send(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class ByteArrayDataSource implements DataSource {
        private byte[] data;
        private String type;

        public ByteArrayDataSource(byte[] data, String type) {
            super();
            this.data = data;
            this.type = type;
        }

        public ByteArrayDataSource(byte[] data) {
            super();
            this.data = data;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getContentType() {
            if (type == null)
                return "application/octet-stream";
            else
                return type;
        }

        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(data);
        }

        public String getName() {
            return "ByteArrayDataSource";
        }

        public OutputStream getOutputStream() throws IOException {
            throw new IOException("Not Supported");
        }
    }


}

您是否需要此类:

import java.security.AccessController;
import java.security.Provider;

public class JSSEProvider extends Provider {
    public JSSEProvider() {
        super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
        AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
            public Void run() {
                put("SSLContext.TLS",
                        "org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
                put("Alg.Alias.SSLContext.TLSv1", "TLS");
                put("KeyManagerFactory.X509",
                        "org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
                put("TrustManagerFactory.X509",
                        "org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
                return null;
            }
        });
    }
}

对于使用此代码:

class SendEmailTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                GmailSender sender = new GmailSender("from email", "from email password");
                //subject, body, sender, to
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
                sender.sendMail("your title",
                        "your content",
                        "from email",
                        "to email");
            } catch (Exception e) {              
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

        }
    }

并运行

SendEmailTask sendEmailTask = new SendEmailTask();
sendEmailTask.execute();

UPD1:库 :1. javax.activation 2. javax.mail

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM