import org.apache.commons.mail.HtmlEmail; //导入方法依赖的package包/类
public boolean sendSupportEmail() {
try {
String senderName = sender_name.getText();
String senderEmail = sender_email.getText();
String sendingTime = date_time.getText();
String systemUser = system_user.getText();
String message = messge_content.getText();
if (message.isEmpty()) {
JOptionPane.showMessageDialog(this, "You haven't entered your message. Please enter the message and try again.");
}
// Create the email message
HtmlEmail email = new HtmlEmail();
email.setHostName("host url");
email.addTo("sender email", "Sender Name");
email.setFrom("from email", "From Name");
email.setAuthentication("username", "password");
email.setSSLOnConnect(true);
email.setStartTLSEnabled(true);
email.addReplyTo("[email protected]", "Support Service - Company");
email.setSmtpPort(465);
email.setSubject("New Support Request from Application");
// embed the image and get the content id
URL url = getClass().getResource("/app/resources/shield_icon16x16.png");
String cid = email.embed(url, "Application Logo");
URL template = getClass().getResource("/app/support/email_template_20161101_isuru.emailtemplate");
byte[] encoded = Files.readAllBytes(Paths.get(template.toURI()));
String htmlMessage = new String(encoded, StandardCharsets.UTF_8);
htmlMessage = htmlMessage.replace("_EP1_", "cid:" + cid);
htmlMessage = htmlMessage.replace("_EP2_", systemUser);
htmlMessage = htmlMessage.replace("_EP3_", senderName + "(" + senderEmail + ")");
htmlMessage = htmlMessage.replace("_EP4_", sendingTime);
htmlMessage = htmlMessage.replace("_EP5_", message.replaceAll("\\r?\\n", "
"));
// set the html message
email.setHtmlMsg(htmlMessage);
String textMessage = "Application - Support Request\n"
+ "---------------------------------------------------------------------\n"
+ "New Support Request from P1\n"
+ "Sent by P2 on P3\n"
+ "---------------------------------------------------------------------\n"
+ "\n"
+ "Message: \nP4\n"
+ "\n"
+ "---------------------------------------------------------------------\n"
+ "This is an automatically generated email sent from Application.\n"
+ "\n"
+ "© All Rights Reserved - Management Development Co-operative Co. Ltd.";
textMessage = textMessage.replace("P1", systemUser);
textMessage = textMessage.replace("P2", senderName + "(" + senderEmail + ")");
textMessage = textMessage.replace("P3", sendingTime);
textMessage = textMessage.replace("P4", message);
// set the alternative message
email.setTextMsg(textMessage);
// send the email
email.send();
return true;
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Cannot send email.\nError:" + e.getLocalizedMessage(), "Sending failure", JOptionPane.ERROR_MESSAGE);
return false;
}
}