这是我为公司制作的应用程序所使用的。 (需要this)
变量
private String SMTP_HOST = "smtp.gmail.com";
private String FROM_ADDRESS = "######@gmail.com";
private String FROM_PASSWORD = "########";
private String TO_ADDRESS = "###############";
private String FROM_NAME = "VDRS Lictor Training Application Emailer";
private Properties props = new Properties();
在某些方法中,创建比例
props.put("mail.smtp.host", SMTP_HOST);
props.put("mail.smtp.user",FROM_NAME);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.port", "25");
props.put("mail.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.EnableSSL.enable","true");
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
当您需要发送时
这是我使用的实际代码。请根据您的需要进行修改。
try{
JButton b = (JButton) arg0.getSource();
//button animation
b.setText("Submitting Application...");
//get values
String player = name.getText();
//make the message
String msg = "<title>New Lictor Training Application from: " + player + "</title> \n";
msg+="<h3>[Name]: </h3>" + player + "\n";
msg+="<h3>[BR]: </h3>" + spinner.getValue() + "\n";
msg+="<h3>[Platoon Leading Experience]: </h3>" + ((JLabel) slider.getLabelTable().get(slider.getValue())).getText() + "\n";
String time = timeEditor.getTextField().getText();
String[] a = time.split(":");
int hours = Integer.parseInt(a[0]);
int min = Integer.parseInt(a[1]);
calander.getDate().setHours(hours);
calander.getDate().setMinutes(min);
calander.getDate().setSeconds(00);
msg+="<h3>[Date/Time]: </h3>" + calander.getDate().toGMTString()+"\n";
msg+="<h3>[Email]: </h3>" + email.getText();
//set up email
Session session = Session.getInstance(props, new AuthorizeEmail());
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(FROM_ADDRESS));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_ADDRESS));
message.setSubject("New Outfit Application from: " + player);
message.setContent(msg, "text/html");
Transport.send(message);
b.setText("Application Submitted!");
} catch (MessagingException e)
{
JOptionPane.showMessageDialog(null, "Failed sending application, please try again later.");
b.setText("Submit Application");
}
}catch(NullPointerException e)
{
JOptionPane.showMessageDialog(null, "Failed sending application.\n Did you fill out all the fields?.");
submit.setText("Submit Application");
}
你也需要这个
class AuthorizeEmail extends Authenticator {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(FROM_ADDRESS, FROM_PASSWORD);
}
}