JavaMailSenderImpl отправка встроенных фотографий - PullRequest
2 голосов
/ 21 марта 2011

Я пытаюсь отправить электронное письмо, используя почтовую реализацию Spring и используя шаблоны скорости для замены содержимого HTML-файлов. До сих пор это работало отлично, но сейчас я сталкиваюсь с проблемой при попытке добавить второе встроенное изображение к почте.

Мой шаблон скорости это:

<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>

Теперь код, который я использую для отправки почты, выглядит следующим образом:

@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 - простая строка «photo», используемая для замены значений в шаблоне скорости.

Проблема в том, что когда вы проверяете почту, отправленную на ваш почтовый ящик, она показывает только первую фотографию, где находится символ $ {photo1}. Я уже проверил и все параметры достигли

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

правильно, даже шаблон скорости изменен правильно. Так что может быть причиной этого провала? Большое спасибо.

1 Ответ

1 голос
/ 21 марта 2011

Да, спасибо за совет. Обнаружил проблему позже .... именно эта часть

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

Поскольку я никогда не закрывал кавычки, изображение никогда не отображалось. Моя вина, очень жаль и еще раз спасибо за ответ.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...