joseJv
joseJv

Reputation: 83

How to embed images into template HTML Velocity?

How to embed images into velocity html template so the recipient can read it without opening the file?

I am following the instructions at: http://sengopal.github.io/blog/blog/java-mail-using-velocity-templates.html

This is my code:

public class SendEmailVelocity {
    public static void main(String[] args) {

        final String username = Contants.myEmail;
        final String password = Contants.myPass;
        final String toMailRecipient = Contants.mailRecipient;

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");

        Session session = Session.getInstance(props,
        new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {

            Template template = Velocity.getTemplate("helloworld.vm");
            VelocityContext context = new VelocityContext();
            context.put("name", "ABC123");
            StringWriter message = new StringWriter();
            template.merge(context, message);


            MimeMultipart multipart = new MimeMultipart("related");

            BodyPart imageBodyPart = new MimeBodyPart();

            StringBuffer imgPath = new StringBuffer().append(File.separator).append("D:\\Temp\\data\\logo.gif");

            DataSource fds = new FileDataSource(imgPath.toString());
            imageBodyPart.setDataHandler(new DataHandler(fds));

            imageBodyPart.setHeader("Content-ID", "<imageID>");

            multipart.addBodyPart(imageBodyPart);

            BodyPart messageBodyPart = new MimeBodyPart();

            StringBuffer messageBuffer = new StringBuffer();
            messageBuffer.append(message.toString());
            messageBuffer.append("<img src='cid:imageID\'>");

            messageBodyPart.setContent(messageBuffer.toString(), "text/html");
            multipart.addBodyPart(messageBodyPart);

            Message msg = new MimeMessage(session);

            msg.setContent(multipart);
            msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(toMailRecipient));

            msg.setSubject("Test Email Velocity ");
            msg.setSentDate(new Date());
            msg.setFrom(new InternetAddress("[email protected]"));

            Transport transport = session.getTransport("smtp");
            transport.connect(props.getProperty("connectHost"), props.getProperty("connectUser"), props.getProperty("connectPassword"));

            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
            System.out.println("Sent!!!");

        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

But the result of the recipient's email is two attachments the recipient's email

Upvotes: 2

Views: 9523

Answers (1)

Brian Kates
Brian Kates

Reputation: 488

This is an older question, but I came across it today Googling how to do the same thing. I used Commons Email and followed these instructions: https://commons.apache.org/proper/commons-email/userguide.html

e.g. in my template:

<img src="cid:${cid}" alt="Logo">

And then in my Java code:

URL url = new URL("something.png");
String cid = email.embed(url, "Logo");
Map emailModel = new HashMap();
emailModel.put("cid", cid);

Upvotes: 1

Related Questions