【发布时间】:2011-11-30 10:21:26
【问题描述】:
我是 Java 编程的初学者。使用 JavaMail API,我编写了一个发送电子邮件的程序。现在我需要创建一个前端并将它们连接起来。我只使用记事本编写程序,不使用任何 IDE。如何轻松创建前端并连接到我的程序?
我的程序是:
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
import java.util.*;
public class Mailer {
public void Mailer() throws Exception {
String usrname;
String pwd;
Scanner in = new Scanner(System.in);
System.out.println("\nEnter the gmail user name :");
usrname = in.next();
System.out.println("\nEnter the Password :");
pwd = in.next();
String HOST_NAME = "smtp.gmail.com";
int HOST_PORT = 465;
Properties props = new Properties();
props.put("mail.transport.protocol", "smtps");
props.put("mail.smtps.host", HOST_NAME);
props.put("mail.smtps.auth", "true");
Session mailSession = Session.getDefaultInstance(props);
Transport transport = mailSession.getTransport();
String toadd;
System.out.println("\nEnter the Recipient Address:");
toadd = in.next();
MimeMessage message = new MimeMessage(mailSession);
System.out.println("\nEnter the Subject:");
String sub = in.nextLine();
message.setSubject(sub);
System.out.println("\nEnter the message body:");
String body = in.nextLine();
message.setContent(body, "text/plain");
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toadd));
transport.connect(HOST_NAME, HOST_PORT, usrname, pwd);
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.close();
System.out.println("Mail Sent successfully!!!!");
System.exit(0);
}
public static void main(String[] args) throws Exception {
System.out.println("*******************Welcome to Mailer*************************");
Mailer mail = new Mailer();
mail.Mailer();
}
}
【问题讨论】:
-
所编写的代码不是以 GUI 可以使用类的方式编写的,因为它使用了
Scanner和System.out之类的东西。为了同时被 GUI 和命令行使用,发送电子邮件的过程需要被抽象为一个类(或方法),由两者调用。 -
欢迎来到 StackOverflow!如果您不使用 IDE,您的开发将花费更长的时间,并且更难(非常!)调试和正确操作。我强烈建议您花时间学习 Eclipse 或 IntelliJ IDEA 社区版:它们都是免费的,使用起来并不难(如果您不使用“高级功能”),并且会在以后为您省去很多麻烦.用记事本管理多个类是一场噩梦,我什至不谈论重构你的代码
-
GUI部分:看一下swing教程:docs.oracle.com/javase/tutorial/uiswing
标签: java swing connection frontend