利用Spring 集成的Mail类发送邮件
下面贴出 其中的主要代码
public static void sendEmail(String toName, String subject, String context, boolean isHtml) throws Exception {
try {
org.springframework.mail.javamail.JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
// 设定mail server
senderImpl.setHost("stmp.163.com");
// 建立邮件消息,发送简单邮件和html邮件的区别
javax.mail.internet.MimeMessage mailMessage = senderImpl.createMimeMessage();
org.springframework.mail.javamail.MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");
messageHelper.setTo(toName);
messageHelper.setFrom("admin@163.com");
messageHelper.setSubject(subject);
// true 表示启动HTML格式的邮件
messageHelper.setText(context, isHtml);
senderImpl.setUsername("admin@163.com"); // 根据自己的情况,设置username
senderImpl.setPassword("passwod"); // 根据自己的情况,
// 设置password
java.util.Properties prop = new Properties();
prop.put("mail.smtp.auth",true); // 将这个参数设为true,让服务器进行认证,认证用户名和密码是否正确
prop.put("mail.smtp.timeout",2500); //2500毫秒
senderImpl.setJavaMailProperties(prop);
// 发送邮件
senderImpl.send(mailMessage);
} catch (Exception e) {
log.error(" sorry ,repeat send email error ,对不起了,你人品不好,发送失败了");
throw e;
}
}