Spring发送html邮件

来源:互联网 发布:快速选择算法的步骤 编辑:程序博客网 时间:2024/05/08 21:46

        本文基于Spring MVC 注解,让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);}}

        以上代码中,发送邮箱的邮件服务器、发送方邮箱、发送方用户名、发送方邮箱密码均来自Constants类,该类从资源文件中获取相关数据并设为类中常量的值,资源环境中的名值对如下所示:

email.from=abc@163.comemail.host=smtp.163.comemail.username=abcemail.password=abcdefg
        其中,email.host为发送方邮箱的发送服务器,163邮箱为smtp.163.com,若使用别的邮箱而未知服务器,则可使用foxmail等工具测试得出结果,或者问渡娘。

        上述代码中很重要的片段如下:

// 添加验证MyAuthenticator auth = new MyAuthenticator(Constants.emailUsername, Constants.emailPassword);Session session = Session.getDefaultInstance(prop, auth);senderImpl.setSession(session);
        上述代码的作用为添加验证,在使用邮箱服务器发送邮件时,需要验证发送方的用户名和密码,验证成功后,邮箱服务器才允许发送邮件。若不加上此代码,则会出现AuthenticationFailedException异常。
        MyAuthenticator为自定义的验证类,该类代码如下所示:
/** * * @author geloin * @date 2012-5-8 下午2:48:25 */package com.embest.ruisystem.util;import javax.mail.Authenticator;import javax.mail.PasswordAuthentication;/** *  * @author geloin * @date 2012-5-8 下午2:48:25 */public class MyAuthenticator extends Authenticator {private String username;private String password;/** *  * @author geloin * @date 2012-5-8 下午2:48:53 * @param username * @param password */public MyAuthenticator(String username, String password) {super();this.username = username;this.password = password;}protected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(username, password);}}

        (3) 发送邮件
/** *  * @author geloin * @date 2012-3-31 下午4:28:30 * @param args */public static void main(String[] args) {String url = Constants.basePath + "/background/index.html";// 发送邮件// 主题String subject = "RUI密码信息";// 正文StringBuilder builder = new StringBuilder();builder.append("<html><head>");builder.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");builder.append("</head><body>");builder.append("您好,张三:<br />");builder.append("\t系统已为您重置了RUI密码,账户信息如下:<br />");builder.append("用户账户:zhangsan<br />用户密码:123456<br />您可以点击以下链接登录RUI:");builder.append("<a href=\"");builder.append(url);builder.append("\">");builder.append(url);builder.append("</a>");builder.append("</body></html>");String htmlContent = builder.toString();MailUtil.sendMail("to@163.com", subject, htmlContent);}


原创粉丝点击