简体   繁体   中英

Spring MVC - Serving static content in java class

i have a function in my spring project that sends an email. Now i want to send png-image in that email.

helper.addInline("myLogo", new ClassPathResource("resources/static/image/logo-mail.png"));

My Question is: how can i serve that image file to my java class. I tried to map the file to an url in my controller but that didn't work. Thank you! Greetings

The question is how is you want to send image -inline probably as that is what your helper class is trying to do.

Ideally you should you use load image using this syntax

<img src="cid:imageName.png"></img>

Next question is how to get he image in the e-mail - right that is where your problem lies? I would suggest to combine the Spring JavaMailSender with the Spring Resource interface to load and store the image data in the generated e-mail.

  1. Load the images as Resource object - assuming you have file as /images/logo.png. Using apache commons library here.
 InputStreamSource imageSource = new ByteArrayResource(IOUtils.toByteArray(getClass().getResourceAsStream("/images/logo.png"))) 
  1. The next step is to add the image to the MIME message as an attachment:
 JavaMailSender mailSender = new JavaMailSenderImpl(); // Or use Spring IoC to inject a pre-configured JavaMailSenderImpl MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8"); // Add information to the message, such as subject, recipients, etc message.addInline("logo.png", imageSource); 

The addInline() method of the MimeMessageHelper reads the byte data from the InputStreamSource and creates the inline MIME body part to hold the attachment. It also sets the content ID to the name provided by the first parameter. Now, all that's left is to reference the image in our HTML body:

message.setText("<img src=\"cid:logo.png\"></img><div>My logo</div>", true);

I solve in a little different way:

public static final String LOGO_DIR="classpath:/static/images/icon64.png";

...

@Inject
private ApplicationContext context;

...

final Resource resource = context.getResource(EmailTemplateConstants.LOGO_DIR);
        InputStreamSource logoSource = new ByteArrayResource(IOUtils.toByteArray(resource.getInputStream()));
        message.addInline(EmailTemplateConstants.LOGO_NAME, logoSource,
                EmailTemplateConstants.LOGO_CONTENT_TYPE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM