Spring发送html邮件
Spring发送html邮件
本文基于Spring 注解,让Spring跑起来。容器:tomcat6
(1) 导入jar包mail.jar、activation.jar和org.springframework.comtext.support.jar,其中mail.jar来自于javaMail,activation.jar来自于jaf,最好都使用最新版。
(2) 编写MailUtil类作为邮件发送的工具类:
- /**
- *
- * @author geloin
- * @date 2012-5-8 上午11:02:41
- */
- package com.embest.ruisystem.util;
- import java.util.Properties;
- import javax.mail.MessagingException;
- import javax.mail.Session;
- import javax.mail.internet.MimeMessage;
- import org.springframework.mail.javamail.JavaMailSenderImpl;
- import org.springframework.mail.javamail.MimeMessageHelper;
- /**
- *
- * @author geloin
- * @date 2012-5-8 上午11:02:41
- */
- public class MailUtil {
- /**
- * 发送html邮件
- *
- * @author geloin
- * @date 2012-5-8 上午11:38:44
- * @param toEmail
- * @param subject
- * @param htmlContent
- */
- public static void sendMail(String toEmail, String subject,
- String htmlContent) {
- JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
- // 发送邮箱的邮件服务器
- senderImpl.setHost(Constants.emailHost);
- // 建立邮件消息,发送简单邮件和html邮件的区别
- MimeMessage mailMessage = senderImpl.createMimeMessage();
- // 为防止乱码,添加编码集设置
- MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,
- "UTF-8");
- try {
- // 接收方邮箱
- messageHelper.setTo(toEmail);
- } catch (MessagingException e) {
- throw new RuntimeException("收件人邮箱地址出错!");
- }
- try {
- // 发送方邮箱
- messageHelper.setFrom(Constants.emailFrom);
- } catch (MessagingException e) {
- throw new RuntimeException("发件人邮箱地址出错!");
- }
- try {
- messageHelper.setSubject(subject);
- } catch (MessagingException e) {
- throw new RuntimeException("邮件主题出错!");
- }
- try {
- // true 表示启动HTML格式的邮件
- messageHelper.setText(htmlContent, true);
- } catch (MessagingException e) {
- throw new RuntimeException("邮件内容出错!");
- }
- Properties prop = new Properties();
- // 将这个参数设为true,让服务器进行认证,认证用户名和密码是否正确
- prop.put("mail.smtp.auth", "true");
- // 超时时间
- prop.put("mail.smtp.timeout", "25000");
- // 添加验证
- MyAuthenticator auth = new MyAuthenticator(Constants.emailUsername,
- Constants.emailPassword);
- Session session = Session.getDefaultInstance(prop, auth);
- senderImpl.setSession(session);
- // senderImpl.setJavaMailProperties(prop);
- // 发送邮件
- senderImpl.send(mailMessage);
- }
- }
- email.from=abc@163.com
- email.host=smtp.163.com
- email.username=abc
- email.password=abcdefg
上述代码中很重要的片段如下:
- // 添加验证
- MyAuthenticator auth = new MyAuthenticator(Constants.emailUsername, Constants.emailPassword);
- Session session = Session.getDefaultInstance(prop, auth);
- senderImpl.setSession(session);
|
评论暂时关闭