java邮件发送和短信发送(一)

来源:互联网 发布:淘宝开店拍身份证技巧 编辑:程序博客网 时间:2024/04/30 03:28
最近刚完成一个任务-付款提醒邮件的发送,对于java邮件的发送有了更深刻的认识,的确java提供的邮件发送机制的确让邮件发送这个问题变得灵活而又简单。并且由于项目组其他人负责了短信的发送,巧的是这个邮件发送的借口与短信发送的借口都被封装到了消息发送的借口,我也顺便学习了一下短信发送的原理,呵呵,算是一箭双雕吧。

    那先来说说邮件发送。按照按接口编程的习惯,当然先要定义一个邮件发送的接口,再实现其接口,完成邮件发送Service层的代码。这个顺序我想大家没什么反对意见吧。

   

    首先咱们先定义一个消息发送接口,它是邮件发送与短信发送的上层接口。

   

[java] view plaincopyprint?
  1. /**  
  2.  * 功能:  系统消息发送服务 <p>  
  3.  * 用法: 
  4.  * @version 1.0 
  5.  */   
  6. public interface MessageService {  
  7.       
  8. /** 
  9.  * 根据消息模板表中的消息编号取得消息模板,填充,发送 
  10.  *  
  11.  * @param bmtCode  消息模板表中的消息编号 
  12.  * @param params 填充模板内容的参数 
  13.  * @param to  消息的接收人 
  14.  * @throws CheckException 模板不存在,或是发送消息出现异常 
  15.  */  
  16. public void sendMessage(String bmtCode,Map params, String... to) throws CheckException;  
  17.   
  18. }  

 

    再来定义一下邮件发送器接口,由于我这里是通过velocity模板发送邮件的,所以如下定义了接口:

[java] view plaincopyprint?
  1. /** 
  2.  * 邮件发送器 
  3.  * @usage        
  4.  */  
  5. public interface TempletEmailSender {  
  6.   
  7.       
  8.     /** 
  9.      * @param from  发件人邮箱 
  10.      * @param to    收件人邮箱 
  11.      * @param subject   邮件主题 
  12.      * @param templet   模板 
  13.      * @param paramMap  模板参数信息 
  14.      * @throws CheckException 
  15.      */  
  16.     public void sendEmailByTemplet(String from, String to, String subject,String templet, Map<String, Object> paramMap) throws CheckException;  
  17.       
  18.     /** 
  19.      * @param from  发件人邮箱 
  20.      * @param to    收件人邮箱(多个) 
  21.      * @param subject   邮件主题 
  22.      * @param templet   模板 
  23.      * @param paramMap  模板参数信息 
  24.      * @throws CheckException 
  25.      */  
  26.     public void sendEmailByTemplet(String from, String[] to, String subject,String templet, Map<String, Object> paramMap) throws CheckException;  
  27.       
  28.       
  29.     /** 
  30.      * @param mail 邮件对象 
  31.      * @param templet 模板     
  32.      * @param paramMap  模板参数信息 
  33.      * @throws CheckException 
  34.      */  
  35.     public void sendEmailByTemplet(Mail mail,String templet, Map<String, Object> paramMap) throws CheckException;  
  36.   
  37.   
  38. }  

 

    接着实现邮件发送的接口:

   

[java] view plaincopyprint?
  1. /** 
  2.  * 邮件发送器默认实现 
  3.  */  
  4. public class TempletEmailSenderImpl implements TempletEmailSender{  
  5.     @Autowired  
  6.     @Qualifier("emailSenderImpl_commons")  
  7.     private EmailSender emailSender;  
  8.       
  9.     @Override  
  10.     public void sendEmailByTemplet(String from, String to,String subject, String templet, Map<String, Object> paramMap) throws CheckException {  
  11.         sendEmailByTemplet(from, new String[]{to}, subject, templet, paramMap);  
  12.           
  13.     }  
  14.   
  15.     @Override  
  16.     public void sendEmailByTemplet(String from, String[] to, String subject, String templet, Map<String, Object> paramMap) throws CheckException {  
  17.         // 解析模板   
  18.         String content ;  
  19.         try {  
  20.             content = VelocityParserUtil.getInstance().parseVelocityTemplate(templet, paramMap);  
  21.         } catch (Throwable t) {  
  22.            throw new CheckException(t);  
  23.         }  
  24.         emailSender.sendEmail(from, to, subject, content);  
  25.           
  26.     }  

 

    大家看到了上面的实现里注入了EmailSender,它也是一个接口,它的实现里注入了JavaMail提供的邮件发送接口。定义了两层是为了区分有模板的发送和无模板的发送。我们来看看它是什么样的:

   

[java] view plaincopyprint?
  1. /** 
  2.  * 邮件发送器 
  3.  * @usage        
  4.  */  
  5. public interface EmailSender {  
  6.   
  7.     /** 
  8.      * 发送邮件 
  9.      * @param from 发件人 
  10.      * @param to 收件人 
  11.      * @param subject 邮件主题 
  12.      * @param mailBody  邮件内容 
  13.      * @throws CheckException 参数校验失败或发送邮件失败时,抛出此异常 
  14.      */  
  15.     void sendEmail(String from, String to, String subject, String mailBody) throws CheckException;  
  16.       
  17.     /** 
  18.      * 发送邮件 
  19.      * @param from 发件人 
  20.      * @param to 多个收件人 
  21.      * @param subject 邮件主题 
  22.      * @param mailBody  邮件内容 
  23.      * @throws CheckException 参数校验失败或发送邮件失败时,抛出此异常 
  24.      */  
  25.     void sendEmail(String from, String[] to, String subject, String mailBody) throws CheckException;  
  26.       
  27.     /** 
  28.      * 发送邮件 
  29.      * @param mail 邮件 
  30.      * @throws CheckException 参数校验失败或发送邮件失败时,抛出此异常 
  31.      */  
  32.     void sendEmail(Mail mail) throws CheckException;  
  33.   
  34.   
  35. }  

    接着实现这个EmailSender接口:

   

[java] view plaincopyprint?
  1. **  
  2.  * JAVA MAIL实现  
  3.  */  
  4. public class EmailSenderImpl implements EmailSender,InitializingBean{  
  5.     /** 
  6.      * Logger for this class 
  7.      */  
  8.     private static final Logger logger = Logger.getLogger(EmailSenderImpl.class);  
  9.   
  10.     @Autowired  
  11.     private ConfigService configService;  
  12.       
  13.     private JavaMailSenderImpl sender; // 实际的发送实现  
  14.       
  15.   
  16.     @Override  
  17.     public void sendEmail(String from, String to, String subject, String mailBody) throws CheckException {  
  18.         sendEmail(from, new String[]{to}, subject, mailBody);  
  19.     }  
  20.       
  21.   
  22.   
  23.     @Override  
  24.     public void sendEmail(String from, String[] to, String subject, String mailBody) throws CheckException {  
  25.         // 构造MAIL对象   
  26.         Mail mail = new Mail();  
  27.         mail.setFrom(from);  
  28.         mail.setTo(to);  
  29.         mail.setSubject(subject);  
  30.         mail.setContent(mailBody);  
  31.         sendEmail(mail);  
  32.           
  33.     }  
  34.   
  35.     @Override  
  36.     public void sendEmail(Mail mail) throws CheckException {  
  37.         // 检查必要参数   
  38.         if (mail == null ){  
  39.             throw new CheckException("mail can not be null.");  
  40.         }  
  41.         if (ArrayUtils.isEmpty(mail.getTo())){  
  42.             throw new CheckException("收件人不能为空");  
  43.         }  
  44.         MimeMessageHelper helper = null;  
  45.         try {  
  46.             helper = new MimeMessageHelper(sender.createMimeMessage(), true"UTF-8");  
  47.   
  48.             // 发件人   
  49.             if (mail.getFrom() != null) {  
  50.                 if (mail.getFromName() == null) {  
  51.                     helper.setFrom(mail.getFrom());  
  52.                 } else {  
  53.                     helper.setFrom(mail.getFrom(), mail.getFromName());  
  54.                 }  
  55.   
  56.             }  
  57.             // 收件人   
  58.             helper.setTo(mail.getTo());  
  59.   
  60.             // 抄送人   
  61.             if (mail.getCc() != null) {  
  62.                 helper.setCc(mail.getCc());  
  63.             }  
  64.   
  65.             // 密送人   
  66.             if (mail.getBcc() != null) {  
  67.                 helper.setBcc(mail.getBcc());  
  68.             }  
  69.   
  70.             // 邮件主题   
  71.             helper.setSubject(mail.getSubject());  
  72.   
  73.             // 邮件内容   
  74.             helper.setText(mail.getContent(), mail.isHtmlFormat());  
  75.   
  76.             // 附件   
  77.             if (mail.getAttachments() != null) {  
  78.                 for ( MailAttachment attachment : mail.getAttachments()) {  
  79.                     helper.addAttachment(attachment.getFileName(),attachment.getFile());  
  80.                 }   
  81.             }  
  82.   
  83.             // 发送时间   
  84.             helper.setSentDate(new Date());  
  85.         } catch (UnsupportedEncodingException e) {  
  86.             logger.error("sendEmail(Mail)", e);  
  87.   
  88.             throw new CheckException(e) ;  
  89.         } catch (MessagingException e) {  
  90.             logger.error("sendEmail(Mail)", e);  
  91.   
  92.             throw new CheckException(e) ;  
  93.         }  
  94.           
  95.         // 发送   
  96.         try {  
  97.             sender.send(helper.getMimeMessage());  
  98.         } catch (MailException e) {  
  99.             logger.error("sendEmail(Mail)", e);  
  100.   
  101.             throw new CheckException(e) ;  
  102.         }  
  103.           
  104.     }  
  105.       
  106.     @Override  
  107.     public void afterPropertiesSet() throws Exception {  
  108.         sender = new JavaMailSenderImpl();  
  109.           
  110.         // configService读出参数   
  111.         Properties pros = new Properties();  
  112.   
  113.         pros.setProperty("mail.smtp.user", configService.getConfig(BasePropertyID.MAIL_SMTP_USER_ID));  
  114.         pros.setProperty("mail.smtp.host", configService.getConfig(BasePropertyID.MAIL_SMTP_HOST_ID));  
  115.         pros.setProperty("mail.smtp.port", configService.getConfig(BasePropertyID.MAIL_SMTP_PORT_ID));  
  116.         pros.setProperty("mail.smtp.connectiontimeout", configService.getConfig(BasePropertyID.MAIL_SMTP_CONNECTIONTIMEOUT_ID));  
  117.         pros.setProperty("mail.smtp.timeout", configService.getConfig(BasePropertyID.MAIL_SMTP_TIMEOUT_ID));  
  118.         pros.setProperty("mail.smtp.from", configService.getConfig(BasePropertyID.MAIL_SMTP_FROM_ID));  
  119.         pros.setProperty("mail.smtp.auth", configService.getConfig(BasePropertyID.MAIL_SMTP_AUTH_ID));  
  120.                   
  121.         sender.setJavaMailProperties(pros);  
  122.         sender.setPassword(configService.getConfig(BasePropertyID.MAIL_SMTP_PASSWORD_ID));  
  123.           
  124.     }  
  125.   
  126.   
  127.   
  128.     public ConfigService getConfigService() {  
  129.         return configService;  
  130.     }  
  131.   
  132.   
  133.   
  134.     public void setConfigService(ConfigService configService) {  
  135.         this.configService = configService;  
  136.     }  

 

    O(∩_∩)O~大家又注意到了 这个接口实现里又注入了一个接口ConfigService 它是去读取邮件发送的相关配置信息,如上所示:

     // configService读出参数
  Properties pros = new Properties();

  pros.setProperty("mail.smtp.user", configService.getConfig(BasePropertyID.MAIL_SMTP_USER_ID));
  pros.setProperty("mail.smtp.host", configService.getConfig(BasePropertyID.MAIL_SMTP_HOST_ID));
  pros.setProperty("mail.smtp.port", configService.getConfig(BasePropertyID.MAIL_SMTP_PORT_ID));
  pros.setProperty("mail.smtp.connectiontimeout", configService.getConfig(BasePropertyID.MAIL_SMTP_CONNECTIONTIMEOUT_ID));
  pros.setProperty("mail.smtp.timeout", configService.getConfig(BasePropertyID.MAIL_SMTP_TIMEOUT_ID));
  pros.setProperty("mail.smtp.from", configService.getConfig(BasePropertyID.MAIL_SMTP_FROM_ID));
  pros.setProperty("mail.smtp.auth", configService.getConfig(BasePropertyID.MAIL_SMTP_AUTH_ID));
    
  sender.setJavaMailProperties(pros);
  sender.setPassword(configService.getConfig(BasePropertyID.MAIL_SMTP_PASSWORD_ID));

   

  而且由于涉及到参数的数据成员较多,就将他们一起封装到了Mail类:

[java] view plaincopyprint?
  1. /**  
  2.  * 功能: 封装邮件对象  <p>  
  3.  * 用法: 
  4.  * @version 1.0 
  5.  */   
  6. public class Mail {  
  7.       
  8.     /** 
  9.      * 发件人 
  10.      */  
  11.     private String from;  
  12.     /** 
  13.      * 发件人(显示) 
  14.      */  
  15.     private String fromName;  
  16.     /** 
  17.      * 收件人 
  18.      */  
  19.     private String[] to;  
  20.     /** 
  21.      * 抄送 
  22.      */  
  23.     private String[] cc;  
  24.     /** 
  25.      * 秘密抄送 
  26.      */  
  27.     private String[] bcc;  
  28.     /** 
  29.      * 邮件主题 
  30.      */  
  31.     private String subject;  
  32.     /** 
  33.      * 邮件内容 
  34.      */  
  35.     private String content;  
  36.     /** 
  37.      * 附件 
  38.      */  
  39.     private MailAttachment[] attachments;  
  40.       
  41.     /** 
  42.      * 是否以HTML格式发送 
  43.      */  
  44.     boolean isHtmlFormat = true;  
  45.       
  46. //getter与setter方法省略   
  47. }  

   好了 整个接口都实现了,其实排除了你发送邮件提供给邮件发送接口的几个参数,剩下的也就是调用java提供的邮件发送的API和一些邮件发送必备的配置信息,必不是很难懂吧。大家肯定注意到了邮件发送接口的velocity模板解析方法:

    content = VelocityParserUtil.getInstance().parseVelocityTemplate(templet, paramMap);

    它具体的实现如下所示:

   

[java] view plaincopyprint?
  1. /** 
  2.  * 功能:解析velocity模板 
  3.  * <p> 
  4.  * 用法: 
  5.  *  
  6.  * @version 1.0 
  7.  */  
  8.   
  9. public class VelocityParserUtil {  
  10.     /** 
  11.      * Logger for this class 
  12.      */  
  13.     private static final Logger logger = Logger.getLogger(VelocityParserUtil.class);  
  14.   
  15.     private static VelocityParserUtil instance = new VelocityParserUtil();  
  16.   
  17.     private VelocityEngine engine = null;  
  18.   
  19.     private VelocityParserUtil() {  
  20.         // init engine   
  21.         engine = new VelocityEngine();  
  22.         try {  
  23.             engine.init();  
  24.         } catch (Exception e) {  
  25.             logger.warn("VelocityParserUtil() - exception ignored", e); //$NON-NLS-1$  
  26.   
  27.         }  
  28.     }  
  29.   
  30.     /** 
  31.      * 返回VelocityParserUtil实例 
  32.      * @return 
  33.      */  
  34.     public static VelocityParserUtil getInstance() {  
  35.         return instance;  
  36.     }  
  37.   
  38.       
  39.   
  40.     /** 
  41.      * 解析velocity模板 
  42.      * @param vtl 
  43.      * @param model 
  44.      * @return String  
  45.      * @throws ParseErrorException 
  46.      * @throws MethodInvocationException 
  47.      * @throws ResourceNotFoundException 
  48.      * @throws IOException 
  49.      */  
  50.     public String parseVelocityTemplate(String vtl, Map model)  
  51.             throws ParseErrorException, MethodInvocationException,  
  52.             ResourceNotFoundException, IOException {  
  53.         if (logger.isDebugEnabled()) {  
  54.             logger.debug("parseVelocityTemplate(String, Map) - start"); //$NON-NLS-1$  
  55.         }  
  56.   
  57.         VelocityContext velocityContext = new VelocityContext(model);  
  58.         StringWriter result = new StringWriter();  
  59.         engine.evaluate(velocityContext, result, null, vtl);  
  60.   
  61.         String returnString = result.toString();  
  62.         if (logger.isDebugEnabled()) {  
  63.             logger.debug("parseVelocityTemplate(String, Map) - end"); //$NON-NLS-1$  
  64.         }  
  65.         return returnString;  
  66.   
  67.     }  
  68.   
  69. }  

   我们会在其他的Service中去调用邮件发送的接口,只需要在业务层里构造好邮件发送的接口所需参数,我们的邮件就可以发送出去了。还有一点请大家注意,我这里主要强调的是运用velocity模板发送邮件,接口所需要的参数templat大家不要误解为velocity模板的文件名,它其实velocity文件的文件流,是一个已经被读入的字符串。大家可以参考一下测试用例,大致可以明白是怎么回事了。

     
 

[java] view plaincopyprint?
  1. public class TempletEmailSenderTest extends BaseTestBaseForJUnit4{  
  2.     @Autowired  
  3.     @Qualifier("templetEmailSenderImpl_commons")  
  4.  private TempletEmailSender sender;  
  5.       
  6. //    @Test   
  7.  public void sendEmailByTemplet() throws CheckException{  
  8.   String templet = "$!{user}提醒您付款$!{amount}元";  
  9.   Map paramMap = new HashMap();  
  10.   paramMap.put("user""吴欣");  
  11.   paramMap.put("amount""99.9");  
  12.     
  13.   sender.sendEmailByTemplet("wuxin.wystan@snda.com""wuxin.wystan@snda.com""模板邮件", templet, paramMap);  
  14.  }  

    整个邮件的发送大家是否明了了呢,呵呵!

    后面我们会将这个接口向上抽象,为了实现我们短信发送的实现,下一篇敬请期待哦

0 0
原创粉丝点击