Send image in thymeleaf - spring

I want to send a message via email in which the alert and image will be sent using thymeleaf, but I do not want to send it in the implementation method of sending the message, since I cannot make changes to this image in any way, can I add an image to the html code? I try to add an image to the html code, the image does not open and I can't do anything with it, I want the image to appear and I could transfer text to it
public void send(String emailTo, String subject, String message,String content) throws MessagingException, IOException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
mimeMessage.setSubject(subject);
mimeMessage.setContent(content, "HTML5");
MimeMessageHelper helper;
helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(username);
helper.setTo(emailTo);
helper.setText(message,true);
// FileSystemResource file = new FileSystemResource(new File("src/main/resources/templates/image/valayev.jpg"));
// helper.addInline("valyaev", file);
mailSender.send(mimeMessage);

Related

send mail through spring boot application

I am creating spring boot application where I have to send newly generated response string for each transaction to user as a text file attachment
so what will be the proper way to do this
any help would be appreciated
Try this below code:
#Override
public void sendMessageWithAttachment(
String to, String subject, String text, String pathToAttachment) {
// ...
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text);
FileSystemResource file
= new FileSystemResource(new File(pathToAttachment));
helper.addAttachment("Invoice", file);
emailSender.send(message);
// ...
}

Spring response entity image

I wrote a rest controller to return an image associated with a primary key. Now I wanted to load this image in the browser and I am running into issues:
(1) If I type a GET URL to the image the browser (FireFox and Chrome) don't display the image but they are seeing all the headers properly. Additionally firefox says "The image cannot be displayed because it contains errors"
(2) If I used XMLHttpRequest to create get the image using the URL I get the image but it displays only partially (the bottom half is cut off and is set to transparent).
#GetMapping("/{featureId}/loadImage")
public ResponseEntity<byte []> loadImageForId(#PathVariable long featureId, HttpServletResponse response) throws IOException {
log.info("Getting image for feature id " + featureId);
Feature feature = featureService.getFeatureById(featureId);
File file = featureService.loadImageForFeature(feature);
byte [] imageData = new byte[(int) file.length()];
FileInputStream inputStream = new FileInputStream(file);
inputStream.read(imageData);
inputStream.close();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType(...));
headers.setContentLength(file.length());
response.setHeader("Content-Disposition", "inline; filename=" + file.getName());
return new ResponseEntity<byte[]>(imageData, headers, HttpStatus.OK);
}
if it is working on tomcat, you can use this tomcat's utility class :
import org.apache.tomcat.util.http.fileupload.IOUtils
for example:
response.setContentType("image/jpeg");
InputStream is = new ByteArrayInputStream(imageByteArray);
IOUtils.copy(is,response.getOutputStream());
Okay finally after hours of debugging with curl etc, I was able to verify that the response body was not getting properly encoded image (nothing to do with the headers).
This was caused due to the choice of InputStream and OutputStream objects.
Instead of using FileInputStream I switched to using ImageIO and the underlying BufferedImage to write the output to the ServletResponse as follows:
#GetMapping("/{featureId}/loadImage")
public void loadImageForId(#PathVariable long featureId, HttpServletResponse response) throws IOException {
log.info("Getting image for feature id " + featureId);
Feature feature = featureService.getFeatureById(featureId);
File imageFile = featureService.loadImageForFeature(feature);
MediaType mediaType = MediaType.parseMediaType(Files.probeContentType(imageFile.toPath()));
response.setHeader("Content-Disposition", "inline; filename=" + imageFile.getName());
response.setStatus(HttpStatus.OK.value());
response.setContentType(mediaType.toString());
response.setContentLength((int)imageFile.length());
OutputStream os = response.getOutputStream();
ImageIO.write(ImageIO.read(imageFile), mediaType.getSubtype(), os);
os.flush();
os.close();
}

Couldn't prepare mail with inline image using Thymeleaf templateEngine?

I am trying to send a html email with an inline-image attached using spring mvc and Thymeleaf. My code works without attaching the image. I get the html email successfully without image. But When I added the following line to my code I get the below error message.
Without this line code works and I get the email without image:
message.addInline(image.getName(), imageSource, image.getContentType());
This is the method:
public void sendUserRegisterEmail(String receiver, String receiverEmailAddress){
MimeMessagePreparator preparator = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws Exception {
Path path = Paths.get("/assets/dist/img/dialog_tv_logo-white-01.png");
String fileName = "dialog_tv_logo-white-01.png";
String originalFileName = "dialog_tv_logo-white-01.png";
String contentType = "image/png";
byte[] content = null;
try {
content = Files.readAllBytes(path);
} catch (final IOException e) {
}
MultipartFile image = new MockMultipartFile(fileName,
originalFileName, contentType, content);
Locale locale = Locale.getDefault();
final Context ctx = new Context(locale);
ctx.setVariable("name", receiver);
ctx.setVariable("subscriptionDate", new Date());
ctx.setVariable("imageResourceName", image.getName());
MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
message.setSubject(USER_REGISTER_MESSAGE_SUBJECT);
message.setTo(receiverEmailAddress);
message.setFrom(SENDER_EMAIL_ADDRESS);
final String htmlContent = emailTemplateEngine.process("email-inlineimage", ctx);
message.setText(htmlContent, true /* isHtml */);
final InputStreamSource imageSource = new ByteArrayResource(image.getBytes());
message.addInline(image.getName(), imageSource, image.getContentType());
}
};
sendEmail(preparator);
}
Following error message I get when the image prepare line is added:
org.springframework.mail.MailPreparationException: Could not prepare mail; nested exception is java.lang.IllegalStateException: Not in multipart mode - create an appropriate MimeMessageHelper via a constructor that takes a 'multipart' flag if you need to set alternative texts or add inline elements or attachments.
Can any one figure out what is the issue here?
Finally able to fix the error after a lot of effort. Changing the following line fixed the issue. Create MimeMessageHelper by passing true
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);

Spring + Thymeleaf mail template - why are inline images attached to email?

I'm using spring + thymeleaf to send emails. My mail template has few images which are displayed properly in the email, however i see that unused images are attached to the bottom of the email. I have business logic in the html, which decides what images to show and what not, so sometimes some images are not used but are attached. How do i get rid of them?
Any ideas?
Here is how i load the image in html:
<img src="cid:change-password" alt="">
Here is how i send the email:
public void sendUsingTemplate(String fromEmail, String toEmail, String subject, String templateName, Map<String, Object> variables) {
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setSubject(subject);
final Context context = new Context(Locale.getDefault());
variables.forEach((name, value) -> context.setVariable(name, value));
String text = templateEngine.process(templateName, context);
helper.setText(text, true);
helper.setFrom(fromEmail);
helper.setTo(toEmail);
Map<String, String> inlineResources = mailTemplateResourcesProvider.getInlineResources(templateName);
inlineResources.forEach((contentId, file) -> addInlineWithoutCheckedException(helper, contentId, file));
mailSender.send(message);
} catch (Exception e) {
logger.error("Error sending mail using template", e);
}

How to get HttpServletRequest object in Spring Schedular (#Schedule)?

I am trying to send a mail using spring scheduler. In that I need HttpServletRequest object to create webContext, so that I can send mail using thyme leaf.
Anyone know the answer of this. Thanks in advance. Code is as follows,
#Async
private void sendNotification(String toField, Users user, int currentMonth)
throws Exception {
// Prepare the evaluation context
#SuppressWarnings("deprecation")
**//here i need request object**
final WebContext ctx = new WebContext(request, request.getSession()
.getServletContext(), request.getLocale());
ctx.setVariable("eagletId", user.getEagletId());
ctx.setVariable("name", user.getFirstName());
ctx.setVariable("setSentDate", new Date());
ctx.setVariable("department", user.getDepartment());
ctx.setVariable("batch", user.getBatch());
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setTo(user.getEmail());
// create html body using thymeleaf
final String htmlContent = this.templateEngine.process("email.html",
ctx);
helper.setText(htmlContent, true);
mailSender.send(message);
}

Resources