实现简单的邮件发送功能
1、需要两个jar包
(1)mail.jar [JavaMail]
下载地址: http://www.oracle.com/technetwork/java/javamail/index.html
(2)activation.jar[JavaBeans Activation Framework]
下载地址: http://www.oracle.com/technetwork/java/jaf11-139815.html
2、代码
public static void sendEmail() {
try {
String to = "xx@xx.com";//收件人邮箱
String from = "xx@xx.com";//发件人邮箱
String host = "smtp.xx.com";//发件邮箱SMTP地址
String username = "xx@xx.com";//发件邮箱
String password = "xxx";//发件邮箱密码
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props, new EmailAutherticator(username, password));
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from, title));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSentDate(new Date());
msg.setSubject(subject);
msg.setText(text);
Transport.send(msg);
} catch(Exception e) {
//............
}
}
3、注意点
有时Spring框架中会有类似geronimo-javamail_1.4_xxxxxxxxxx.jar的包,需要删除掉!