package com.chauvet.util;

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger; /**
* 用于发送jmail邮件
* 需要用到 SMTPAuthenticator.java
* @author WXW
*
*/
public class Jmail {
private String hostSmtp = "smtp.126.com"; // 邮箱smtp
private String hostAddress = "*******@126.com"; // 发件箱地址
private String hostPwd = "pwd"; // 发件箱密码
private static Logger log = Logger.getLogger(Jmail.class.getName()); /**
* 发送jmail
*
* @param title
* email标题
* @param content
* Email内容
* @param toAddress
* 接收邮箱地址 如:[email protected]
*/
public void sendMail(String title, String content, String toAddress) {
try {
String mail = content;
// properties里面包含发送邮件服务器的地址
Properties mailProps = new Properties();
mailProps.put("mail.smtp.host", hostSmtp);
mailProps.put("mail.smtp.auth", "true");
SMTPAuthenticator smtpAuthenticator = new SMTPAuthenticator(hostAddress, hostPwd);
Session mailSession = Session.getDefaultInstance(mailProps,smtpAuthenticator);
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(hostAddress));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress, false));
message.setSubject(title);
message.setText(mail);
Transport.send(message);
} catch (Exception exc) {
log.error("发送邮件 "+title+" 异常!");
exc.printStackTrace();
}
} public static void main(String[] args) {
Jmail aa = new Jmail();
aa.sendMail("标题", "内容", "[email protected]");
System.out.println("Well Done!");
}
}
05-11 21:52