packagecom.srie.mail;importjava.util.Properties;importjavax.mail.Authenticator;importjavax.mail.Message;importjavax.mail.MessagingException;importjavax.mail.PasswordAuthentication;importjavax.mail.Session;importjavax.mail.Transport;importjavax.mail.internet.AddressException;importjavax.mail.internet.InternetAddress;importjavax.mail.internet.MimeMessage;public classSendmailUtil {//设置服务器
private static String KEY_SMTP = "mail.smtp.host";private static String VALUE_SMTP = "10.1.4.125";//服务器验证
private static String KEY_PROPS = "mail.smtp.auth";private static boolean VALUE_PROPS = true;//发件人用户名、密码
private String SEND_USER = "wangshengdong@itc.cr";private String SEND_UNAME = "wangshengdong";private String SEND_PWD = "a";//建立会话
privateMimeMessage message;privateSession s;/** 初始化方法*/
publicSendmailUtil() {
Properties props=System.getProperties();
props.setProperty(KEY_SMTP, VALUE_SMTP);
props.put(KEY_PROPS,"true");//props.put("mail.smtp.auth", "true");
s = Session.getDefaultInstance(props, newAuthenticator(){protectedPasswordAuthentication getPasswordAuthentication() {return newPasswordAuthentication(SEND_UNAME, SEND_PWD);
}});
s.setDebug(true);
message= newMimeMessage(s);
}/*** 发送邮件
*
*@paramheadName
* 邮件头文件名
*@paramsendHtml
* 邮件内容
*@paramreceiveUser
* 收件人地址*/
public voiddoSendHtmlEmail(String headName, String sendHtml,
String receiveUser) {try{//发件人
InternetAddress from = newInternetAddress(SEND_USER);
message.setFrom(from);//收件人
InternetAddress to = newInternetAddress(receiveUser);
message.setRecipient(Message.RecipientType.TO, to);//邮件标题
message.setSubject(headName);
String content=sendHtml.toString();//邮件内容,也可以使纯文本"text/plain"
message.setContent(content, "text/html;charset=GBK");
message.saveChanges();
Transport transport= s.getTransport("smtp");//smtp验证,就是你用来发邮件的邮箱用户名密码
transport.connect(VALUE_SMTP, SEND_UNAME, SEND_PWD);//发送
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("send success!");
}catch(AddressException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(MessagingException e) {
e.printStackTrace();
}
}public static voidmain(String[] args) {
SendmailUtil se= newSendmailUtil();
se.doSendHtmlEmail("邮件头文件名", "邮件内容", "wangshengdong@itc.cr");
}
}