本文基于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);
-
- }
-
- }
以上代码中,发送邮箱的邮件服务器、发送方邮箱、发送方用户名、发送方邮箱密码均来自Constants类,该类从资源文件中获取相关数据并设为类中常量的值,资源环境中的名值对如下所示:
- email.from=abc@163.com
- email.host=smtp.163.com
- email.username=abc
- email.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为自定义的验证类,该类代码如下所示: