packageutil;importjava.util.Date;importjava.util.Properties;importjavax.mail.Authenticator;importjavax.mail.BodyPart;importjavax.mail.Message;importjavax.mail.Multipart;importjavax.mail.PasswordAuthentication;importjavax.mail.Session;importjavax.mail.Transport;importjavax.mail.internet.InternetAddress;importjavax.mail.internet.MimeBodyPart;importjavax.mail.internet.MimeMessage;importjavax.mail.internet.MimeMultipart;public classMail {private staticMimeMessage message;static{try{
Properties properties= newProperties();
properties.load(Mail.class.getResourceAsStream("/Mail.properties"));//发件人邮箱用户名
final String userName = properties.getProperty("username");final String password = AESCodec.decrypt(properties.getProperty("password"));
Session session= Session.getDefaultInstance(properties, newAuthenticator() {publicPasswordAuthentication getPasswordAuthentication() {//发件人邮件用户名、密码
return newPasswordAuthentication(userName, password);
}
});
message= newMimeMessage(session);
message.setFrom(newInternetAddress(userName));//设置邮件消息发送的时间
message.setSentDate(newDate());
}catch(Exception e) {
e.printStackTrace();
}
}/*** 发送纯文本格式邮件
*
*@paramrecipient 收件人
*@paramsubject 主题
*@paramtext 邮件文本内容
*@return邮件是否发送成功*/
public static booleansendTextEmail(String recipient, String subject, String text) {try{//Set To: 头部头字段
message.addRecipient(Message.RecipientType.TO, newInternetAddress(recipient));//Set Subject: 头部头字段
message.setSubject(subject);//设置消息体
message.setText(text);//发送消息
Transport.send(message);
System.out.println("Sent message successfully....");return true;
}catch(Exception e) {
e.printStackTrace();
System.out.println("Sent message failed....");return false;
}
}/*** 发送HTML格式邮件
*
*@paramrecipient 收件人
*@paramsubject 主题
*@paramhtml 邮件内容HTML格式
*@return邮寄是否发送成功*/
public static booleansendHtmlEmail(String recipient, String subject, String html) {try{//Set To: 头部头字段
message.addRecipient(Message.RecipientType.TO, newInternetAddress(recipient));//Set Subject: 头部头字段
message.setSubject(subject);//创建消息部分
BodyPart body = newMimeBodyPart();//设置消息
body.setContent(html, "text/html; charset=utf-8");//创建多重消息
Multipart multipart = newMimeMultipart();
multipart.addBodyPart(body);//将MiniMultipart对象设置为邮件内容
message.setContent(multipart);//发送消息
Transport.send(message);
System.out.println("Sent message successfully....");return true;
}catch(Exception e) {
e.printStackTrace();
System.out.println("Sent message failed....");return false;
}
}public static voidmain(String[] args) {
testHtml();
}/*** 测试发送HTML格式邮件*/
public static voidtestHtml() {//收件人邮箱
String recipient = "hnfch@qq.com";
String subject= "生日快乐!";
StringBuffer content= newStringBuffer();
content.append("");
content.append("
");content.append("
");
content.append("祝你生日快乐!");
content.append("");
content.append("");
content.append("");
content.append("");
System.out.println(sendHtmlEmail(recipient, subject, content.toString()));
}
}