The company made a new project, you need to use to send e-mail function. Because the e-mail module former colleagues have done on other projects, so a direct transplant.
This thought is very simple, direct copy more than good. However, the ill-fated. Code is called when sending mail error.
The main code:
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.starttls.enable", "true");// 使用 STARTTLS安全连接
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
session.setDebug(false);
MimeMessage message = new MimeMessage(session);
try {
String show_username = username;
if (show_username.indexOf("@") > -1) {
show_username = show_username.split("@")[0];
}
message.setFrom(new InternetAddress(username, show_username));
InternetAddress[] internetAddressTo = new InternetAddress().parse(toMail);
message.setRecipients(Message.RecipientType.TO, internetAddressTo);
//message.addRecipient(Message.RecipientType.TO, new InternetAddress(toMail));
message.setSubject(subject);
message.addHeader("charset", "UTF-8");
/* 添加正文内容 */
Multipart multipart = new MimeMultipart();
StringBuffer lineTxt = new StringBuffer();
BodyPart contentPart = new MimeBodyPart();
contentPart.setText(lineTxt.toString());
contentPart.setHeader("Content-Type", "text/html; charset=UTF-8");
multipart.addBodyPart(contentPart);
message.setContent(multipart);
message.setSentDate(new Date());
message.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host, port, username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace ();
}
Break point is seen Transport transport = session.getTransport ( "smtp"); when given
Baidu for a long time, the three asked the degree of your mother. Finally found the problem cited jar package
jdk7 with mail-1.4.jar original system used
Now the system is jdk8 re-downloaded the latest javax.mail.jar get.