2011-03-21 2 views
2

저는 Spring의 메일 구현을 사용하여 전자 메일을 보내고 html 파일의 내용을 바꾸기 위해 속도 템플릿을 사용하려고합니다. 지금까지는 효과가 있었지만 지금은 메일에 두 번째 인라인 이미지를 추가하려고 할 때 문제가 발생합니다.JavaMailSenderImpl 인라인 사진 보내기

내 속도 템플릿이 하나입니다

@SuppressWarnings("unchecked") 
public void sendTemplateMail(VelocityMailMessage message) { 
    Connection connection = null; 
    Session session = null; 


    try { 
     connection = connectionFactory.createConnection(); 
     session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); 

     Velocity.init(initializeVelocityProperties()); 
     VelocityContext velocityContext = new VelocityContext(); 

     HashMap<String, Object> parameterMap=message.getReplaceableParameters(); 
     HashMap<String, Attachment> attachmentMap=message.getAttachList(); 

     //${paragraph1} and ${paragraph2} are replaced here 
     for (String key : parameterMap.keySet()) { 
      velocityContext.put(key, parameterMap.get(key)); 
     } 
     //Here the inline photos identifiers should be replaced ${photo1} and ${photo2} 
     int k=1; 
     for (String key: attachmentMap.keySet()) 
     { 
      //INLINE_PHOTO_PREFIX has a value of "photo"    
      velocityContext.put(Constants.INLINE_PHOTO_PREFIX+k, attachmentMap.get(key).getIdentifier()); 
      k++; 
     } 

     StringWriter text = new StringWriter(); 
     Velocity.mergeTemplate(message.getTemplateName(), "UTF-8", velocityContext, text); 

     List<String> emailList = message.getTo(); 

     ArrayList<String> emails = new ArrayList<String>(); 
     for (Iterator<String> iterator = emailList.iterator(); iterator 
       .hasNext();) { 
      String[] tmp = null; 
      String[] tmp1 = null; 
      int i = 0; 
      int j = 0; 
      String name = (String) iterator.next(); 
      tmp = name.split(";"); 
      while (i < tmp.length) { 
       tmp1 = tmp[i].split(","); 
       i++; 
       j = 0; 
       while (j < tmp1.length) { 
        emails.add(tmp1[j]); 
        j++; 
       } 
      } 

     } 
     if (!emails.isEmpty()) { 
      emailList = emails; 
     } 

     JavaMailSenderImpl sender = new JavaMailSenderImpl(); 
     MimeMessage mimeMessage = sender.createMimeMessage(); 
     String[] toArray = new String[emailList.size()]; 
     int i = 0; 
     for (String to : emailList) { 
      toArray[i] = to; 
      i++; 
     } 


      MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); 

      helper.setText(text.toString(), true); 
      helper.setTo(toArray); 
      helper.setFrom(message.getFrom(), "Portal"); 
      helper.setReplyTo(message.getFrom()); 
      helper.setSubject(message.getSubject()); 
      if (message.getAttachList() != null) { 
       if (!(message.getAttachList().isEmpty())) { 
        Set<String> keys = message.getAttachList().keySet(); 
        for (String string : keys) { 
          Attachment at=message.getAttachList().get(string); 
          if(at.isInline()){ 
           helper.addInline(at.getIdentifier(), at.getAttachFile()); 
          }else{ 
           helper.addAttachment(string, message.getAttachList() 
           .get(string).getAttachFile()); 
          } 
        } 
       } 
      } 
      sender.setHost(parameterServiceLocal.parameterByName("SMTP HOST") 
        .getValue()); 
      sender.setUsername(parameterServiceLocal.parameterByName("SMTP USER").getValue()); 
      sender.setPassword(parameterServiceLocal.parameterByName("SMTP PASSWORD").getValue()); 
      Properties p = new Properties(); 

      p.put("mail.smtp.starttls.enable","true"); 
      p.put("mail.smtp.auth", "true"); 
      sender.setJavaMailProperties(p); 
      sender.send(mimeMessage); 

    } catch (VelocityException e) { 
     e.printStackTrace(); 
    } catch (MessagingException e) { 
     e.getMessage(); 
    } 
    catch (JMSException e) { 
     e.printStackTrace(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } finally { 
     if (session != null && session != null) { 
      try { 
       session.close(); 
       connection.close(); 
      } catch (JMSException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

Constants.INLINE_PHOTO_PREFIX는 간단하다 :

<html> 
<head> 
    <title>Ndeveloper publishing</title> 
</head> 
<body> 
    <div id="header" style="background-color: #eeeeee"> 
     <div align="center"> 
      <p><em>Header1</em></p> 
     </div> 
    </div> 
    <div id="content"> 
     <div id="paragraph1"> 
      <img src='cid:${photo1}' width="200px" height="200px" style="display: block;float: left; margin: 0em 1em 1em 0em "/> 
      <p>${paragraph1} 
      </p> 
     </div> 
     <div id="paragraph2> 
      <img src='cid:${photo2}' width="200px" height="200px" style="display: block;float: right; margin: 0em 0em 1em 1em "/> 
      <p>${paragraph2} 
      </p> 
     </div> 
    </div> 
    <div id="footer" style="background-color: #eeeeee"> 
     <div align="center"> 
      <p><em>Footer1</em></p> 
     </div> 
    </div> 
</body> 

지금 내가 메일을 보낼 사용하고 코드는 다음과 같습니다 vecloity 템플릿의 값을 바꾸는 데 사용되는 문자열 "photo".

문제는받은 편지함으로 보낸 메일을 확인하면 $ {photo1} 기호가있는 첫 번째 사진 만 표시된다는 것입니다. 이미 체크했는데 모든 파라미터가

if(at.isInline()){ 
      helper.addInline(at.getIdentifier(), at.getAttachFile()); 
} 

이 맞으면 속도 템플릿도 올바르게 수정됩니다. 그래서 이것이 실패 할 수있는 이유는 무엇입니까? 고마워.

+1

코드를 읽기가 어렵습니다. 우리가 그것을 이해할 수 있도록 좀 더 작은 방법으로 해체해야합니다. 우편물에서 속도 물건을 분리하여 시작하십시오. – skaffman

답변

1

그래, 고마워. 나중에 문제가 발견되었습니다 .... 그냥이 부분이었습니다

<div id="paragraph2> 
     <img src='cid:${photo2}' width="200px" height="200px" style="display: block;float: right; margin: 0em 0em 1em 1em "/> 
     <p>${paragraph2} 

절대로 절대로 이미지가 표시되지 않았습니다. 내 잘못, 정말 죄송합니다. 응답에 다시 한 번 감사드립니다.