如何在IDE外部使用Java Mail发送邮件

问题描述 投票:1回答:2

我正在尝试在我的JavaFX应用程序中发送一封电子邮件一切正常,电子邮件发送给Reciepent,我在IDE(InteliJ)中运行它时没有异常也没有错误但是当我在Intelij之外运行应用程序时它不起作用。我制作了简单的注册表单,将数据从字段保存到我的数据库中:

String username;
String password;
String email;
Random rd = new Random();
int ID;
public void registerUser(javafx.event.ActionEvent ab) {
     username = textUser.getText();
     password = textPass.getText();
     email = textEmail.getText();

    ID = rd.nextInt(999999999);
    Connection connectt = null;


    try {

        Class.forName("org.sqlite.JDBC");
        connectt = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\barte\\OneDrive\\Desktop\\sqlite databases\\PRODUCTS\\Products.db");
        String s = "INSERT INTO Users(Username,Password,Email,UserID)  VALUES (?,?,?,?) ";
        PreparedStatement registera = connectt.prepareStatement(s);
        registera.setString(1, username);
        registera.setString(2, password);
        registera.setString(3, email);
        registera.setInt(4, ID);

        System.out.println(username);
        System.out.println(password);
        System.out.println(email);
        registera.executeUpdate();
        System.out.println("Added to Database");
        sendMail();
        registerr.setStyle("-fx-background-color: #69ff59;");
        registerr.setText("Check Your MailBox");
        registerr.setOnMouseClicked(event -> {
            registerr.setText("Email Has been sent");
        });
        textUser.setText(null);
        textEmail.setText(null);
        textPass.setText(null);
        regiPane.setVisible(false);

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    }
}

这是发送电子邮件的代码:

public void sendMail() throws MessagingException {
    String USER_NAME = "stoc****";
    String from = USER_NAME;
    String PASSWORD = "************";
    String pass = PASSWORD;
    String RECIPT = textEmail.getText();
    String TOPIC = "Welcome " + username + "!";
    String BODY = "Dear user! " +
            "You can sign into StockFX by your ID/Username and password" +
            "User ID: " + ID + "\n" + "Password: " + password + "\n" +
            "We would like to thank you for using our services now and in future!";
    String[] to = {RECIPT};
    Properties props = System.getProperties();
    String host = "smtp.gmail.com";
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.password", pass);
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.auth", "true");
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(
                    "****", PASSWORD);
        }
    });
    MimeMessage message = new MimeMessage(session);


    try {
        try {
            message.setFrom(new InternetAddress(from));
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        InternetAddress[] toAddress = new InternetAddress[to.length];
        // To get the array of addresses
        for (int i = 0; i < to.length; i++) {
            try {
                toAddress[i] = new InternetAddress(to[i]);
            } catch (AddressException e) {
                e.printStackTrace();
            }
        }
        for (int i = 0; i < toAddress.length; i++) {
            try {
                message.addRecipient(Message.RecipientType.TO, toAddress[i]);
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
        try {
            message.setSubject(TOPIC);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        try {
            message.setText(BODY);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        try {
            message.saveChanges();
        } catch (MessagingException e) {
            e.printStackTrace();
        }


        registerr.setStyle("-fx-background-color: #69ff59;");
        registerr.setText("You can now log in");
        registerr.setDisable(false);
        textUser.setText(null);
        textEmail.setText(null);
        textPass.setText(null);
        regiPane.setVisible(false);
        Transport transport = session.getTransport("smtp");
        System.out.println("get protocl");
        transport.connect(host, from, pass);
        System.out.println("get host,from and password");
        transport.sendMessage(message, message.getAllRecipients());
        System.out.println("get recipients");
        transport.close();
        System.out.println("close");
        System.out.println("Email Sent Successfully!");
    } finally {
        System.out.println("Complete Process");
    }

}

在IntelliJ中一切正常,但void sendEmail在runnable jar中不起作用我是Java邮件的新手。进口:

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.*;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
import java.util.Random;
import java.util.ResourceBundle;

这个类是Controller Class

这是主要类:

package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import java.io.IOException;

public class Main extends Application {

@Override
public void start(Stage UI) throws IOException {
    Parent root = FXMLLoader.load(getClass().getResource("DashBoard.fxml"));
    UI.setTitle("DIREXT SCANNER (DEMO VER 0.5)");
    UI.setScene(new Scene(root, 800, 600));
    UI.initStyle(StageStyle.UNDECORATED);
    UI.setResizable(false);
    UI.show();
    UI.setFullScreenExitHint("Press 'ESC' to exit full screen");

}
public static void main(String[] args){
    launch(args);
}
}

我尝试重建项目,删除并再次添加库但是相同的结果是否有人遇到过同样的问题?是IDE相关还是我缺少进口或方法?我试图在论坛上寻找类似的问题,我已经修复了一些东西,因为之前可运行的jar根本就不会运行。如果存在问题,请有人提供链接。

编辑这是我从PowerShell运行jar时得到的错误:

Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
        at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(Unknown Source)
        at javafx.fxml/javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(Unknown Source)
        at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
        at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
        at javafx.base/javafx.event.Event.fireEvent(Unknown Source)
        at javafx.graphics/javafx.scene.Node.fireEvent(Unknown Source)
        at javafx.controls/javafx.scene.control.Button.fire(Unknown Source)
        at javafx.controls/com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(Unknown Source)
        at javafx.controls/com.sun.javafx.scene.control.inputmap.InputMap.handle(Unknown Source)
        at javafx.base/com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
        at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
        at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
        at javafx.base/javafx.event.Event.fireEvent(Unknown Source)
        at javafx.graphics/javafx.scene.Scene$MouseHandler.process(Unknown Source)
        at javafx.graphics/javafx.scene.Scene$MouseHandler.access$1300(Unknown Source)
        at javafx.graphics/javafx.scene.Scene.processMouseEvent(Unknown Source)
        at javafx.graphics/javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
        at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
        at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(Unknown Source)
        at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(Unknown Source)
        at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
        at javafx.graphics/com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
        at javafx.graphics/com.sun.glass.ui.View.notifyMouse(Unknown Source)
        at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
        at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(Unknown Source)
        at java.base/java.lang.Thread.run(Unknown Source)
Caused by: java.lang.reflect.InvocationTargetException
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.base/java.lang.reflect.Method.invoke(Unknown Source)
        at com.sun.javafx.reflect.Trampoline.invoke(Unknown Source)
        at jdk.internal.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.base/java.lang.reflect.Method.invoke(Unknown Source)
        at javafx.base/com.sun.javafx.reflect.MethodUtil.invoke(Unknown Source)
        at javafx.fxml/com.sun.javafx.fxml.MethodHelper.invoke(Unknown Source)
        ... 52 more
Caused by: java.lang.NoClassDefFoundError: javax/activation/DataHandler
        at sample.DashBoardController.registerUser(DashBoardController.java:321)
        ... 62 more
Caused by: java.lang.ClassNotFoundException: javax.activation.DataHandler
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source)
        at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
        ... 63 more
java intellij-idea javafx-2 javamail jetbrains-ide
2个回答
0
投票

如果您正在使用外部库那么问题有时会发生在这个库的路径中当您解压缩到jar文件时,简单的解决方案,有时工作是创建新项目并创建新文件作为旧项目并移动它们


0
投票

我找到了解决方案,谢谢你所有的帮助我做了什么,在项目结构中,我删除了所有工件,模块和库,然后重新添加所有内容然后重建项目然后构建工件,我也将我的项目文件夹设置为Source Root,它工作。

© www.soinside.com 2019 - 2024. All rights reserved.