How to process TXT e-mail template with Thymeleaf? - spring

I'm trying to send plain text email from Spring application with Thymeleaf.
This is my e-mail service:
#Override
public void sendPasswordToken(Token token) throws ServiceException {
Assert.notNull(token);
try {
Locale locale = Locale.getDefault();
final Context ctx = new Context(locale);
ctx.setVariable("url", url(token));
// Prepare message using a Spring helper
final MimeMessage mimeMessage = mailSender.createMimeMessage();
final MimeMessageHelper message = new MimeMessageHelper(
mimeMessage, false, SpringMailConfig.EMAIL_TEMPLATE_ENCODING
);
message.setSubject("Token");
message.setTo(token.getUser().getUsername());
final String content = this.textTemplateEngine.process("text/token", ctx);
message.setText(content, false);
mailSender.send(mimeMessage);
} catch (Exception e) {
throw new ServiceException("Token has not been sent", e);
}
}
email is sent and delivered into mailbox.
This is my plain text email template:
Token url: ${url}
but in delivered mailbox url variable is not replaced with it's value. Why?
When I use html classic HTML Thymeleaf syntax, variable is replaced:
<span th:text="${url}"></span>
What is proper syntax for e-mail text template?

You can use Thymeleaf in plain text mode as well, like in this example:
Dear [(${customer.name})],
This is the list of our products:
[# th:each="p : ${products}"]
- [(${p.name})]. Price: [(${#numbers.formatdecimal(p.price,1,2)})] EUR/kg
[/]
Thanks,
The Thymeleaf Shop
That means you can have a text-file with just this in it:
Token url: [(${url})]
Take a look at the complete documentation of those features here:
https://github.com/thymeleaf/thymeleaf/issues/395
Edit
As mentioned in a comment, make sure to use version >= 3.0 of Thymeleaf:
<properties>
<thymeleaf.version>3.0.3.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.1.2</thymeleaf-layout-dialect.version>
</properties>

Use an HTML template like this and it will procude plain text.
<html xmlns:th="http://www.thymeleaf.org" th:inline="text" th:remove="tag">
Token url: [[${url}]]
</html>
another way, still using html could be like this
<span th:text="Token url:" th:remove="tag"></span><span th:text="${url}" th:remove="tag"></span>
What you are looking is to produce plain text so thymeleaf will return that for you.

Related

Get message content from mime message?

I have a java spring integration project that is receving emails through the below code:
ClassPathXmlApplicationContext ac =
new ClassPathXmlApplicationContext(
"/integration/gmail-imap-idle-config.xml");
DirectChannel inputChannel = ac.getBean("receiveChannel", DirectChannel.class);
inputChannel.subscribe(message -> {
org.springframework.messaging.Message<MimeMailMessage> received =
(org.springframework.messaging.Message<MimeMailMessage>) message;
log.info("content" + message);
List<String> sentences = null;
try {
} catch (Exception e) {
}
I get the email, and I can get the subject, but I can never actually extract the message body. How do I do this?
Thank you!
You have to use this option on the channel adapter:
simple-content="true"
See its description:
When 'true', messages produced by the source will be rendered by 'MimeMessage.getContent()'
which is usually just the body for a simple text email. When false (default) the content
is rendered by the 'getContent()' method on the actual message returned by the underlying
javamail implementation.
For example, an IMAP message is rendered with some message headers.
This attribute is provided so that users can enable the previous behavior, which just
rendered the body.
But still it is doubtful, since I see in case of GMail message it is never simple. The content is a MimeMultipart and we need to read its parts to get access to the real body.
So, this is how you should change your code as well:
log.info("content" + ((MimeMultipart) ((MimeMessage) message.getPayload()).getContent()).getBodyPart(0).getContent());

How to send multipart file to springboot server using tornadoFx?

Here can the following funcationality be acheived with TornadoFX. (Sorry for example in java)
<form method = "post" action="/store" enctype="multipart/form-data">
<label>Image</label>
<input type="file" name="imageFile" />
</form>
and on controller side
#PostMapping
public String store(#Valid Item item, #RequestParam("imageFile") MultipartFile file) throws IOException {
if (file != null) {
Path path = Paths.get(System.getProperty("user.dir") + "/images/" + file.getOriginalFilename());
Files.write(path, file.getBytes());
}
repository.save(course);
model.addAttribute("success", "Item saved successfully");
model.addAttribute("item", new Item());
return "redirect:/items/form";
}
I did not find any example, so any small example would be very helpful.
or if there is any other way to acheive this functionality?
regards
Though you can manipulate the Rest client in TornadoFX to do this, it's easier to use Apache HttpClient directly, since it's already on your classpath and provides proper interfaces for sending multipart/form-data. You'll find plenty of HttpClient usage examples for multipart/form-data here on SO :)

Spring boot endpoint can not redirect to my view

I have an endpoint:
#GetMapping(value = "/reset-password")
public String displayResetPasswordPage(
It was taking only String token object but then i tried lots of things and last version is:
GetMapping(value = "/reset-password")
public String displayResetPasswordPage(HttpServletRequest request, #RequestParam("token") String token, Model model) {
//here token validate jobs, it is for brevity
Token resetToken = validateToken(token);
ModelAndView modelAndView = prepareModelAndView(currentUser, PASSWORD_RESET);
// modelAndView.addObject("success", request.getParameter("success"));
if (resetToken == null){
modelAndView.addObject("error", "Could not find password reset token.");
model.addAttribute("message","Could not find password reset token." );
} else if (resetToken.isExpired()){
modelAndView.addObject("error", "Token has expired, please request a new password reset.");
model.addAttribute("message","Could not find password reset token." );
} else {
modelAndView.addObject("token", resetToken.getToken());//ihtiyaç var mı emin değilim
model.addAttribute("message","Could not find password reset token." );
}
return "redirect:/Reset-Password.html";
}
What i want is, it should go to simple html of that:
<!DOCTYPE html>
<html layout:decorator="layouts/Master" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Bilgilerim</title>
</head>
<body>
fsfasasd
asdsasda
</body>
</html>
its name is Reset-Password.html
It is inside resources-teplates-Reset-Password.html
I also added this
.antMatchers("/reset-password**").permitAll()
For example here , this code goes and shows string on page:
redirect:/Reset-Password.html
when i try to go to
myurl/reset-password?token=122b4e43-0b63-4a6b-8669-f4e6c623ee2d
But instead, when i do
httpServletResponse.sendRedirect("https://twitter.com");
in that method, it goes.
But for
httpServletResponse.sendRedirect("/reset-password");
with void return, it redirects to /reset-password path and
gives error of custom /error page.
What can i do?
Also , when i try to do like this
modelAndView = prepareModelAndView(controllerParams.currentUser, "simplepage");
//todo send only user object
modelAndView.addObject("mobileNumber", mobile);
return modelAndView;
it goes to that view. normally it is another endpoint and view but i copied from there and this can also go that view.
For same approach, i got
template might not exist or might not be accessible by any of the configured Template Resolvers
but Reset-Password and simplepage are in same folder, under templates

Send Status code and message in SpringMVC

I have the following code in my web application:
#ExceptionHandler(InstanceNotFoundException.class)
#ResponseStatus(HttpStatus.NO_CONTENT)
public ModelAndView instanceNotFoundException(InstanceNotFoundException e) {
return returnErrorPage(message, e);
}
Is it possible to also append a status message to the response? I need to add some additional semantics for my errors, like in the case of the snippet I posted I would like to append which class was the element of which the instance was not found.
Is this even possible?
EDIT: I tried this:
#ResponseStatus(value=HttpStatus.NO_CONTENT, reason="My message")
But then when I try to get this message in the client, it's not set.
URL u = new URL ( url);
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod("GET");
HttpURLConnection.setFollowRedirects(true);
huc.connect();
final int code = huc.getResponseCode();
String message = huc.getResponseMessage();
Turns out I needed to activate custom messages on Tomcat using this parameter:
-Dorg.apache.coyote.USE_CUSTOM_STATUS_MSG_IN_HEADER=true
The message can be in the body rather than in header. Similar to a successful method, set the response (text, json, xml..) to be returned, but set the http status to an error value. I have found that to be more useful than the custom message in header. The following example shows the response with a custom header and a message in body. A ModelAndView that take to another page will also be conceptually similar.
#ExceptionHandler(InstanceNotFoundException.class)
public ResponseEntity<String> handle() {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("ACustomHttpHeader", "The custom value");
return new ResponseEntity<String>("the error message", responseHeaders, HttpStatus.INTERNAL_SERVER_ERROR);
}

sending mail usingsprings with html content as text

by using above code i send the mail, body with normal text. now i want to send the mail with html content as body any suggestions appriciate.
public void sendMail() {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("xxxxxxxxxxxx#gmail.com");
message.setTo("xxxxxxx.yyyyyy#gmail.com");
message.setSubject("Hi");
message.setText("Welcome to FoodeeBuddee");
javaMailSender.send(message)
}
You can create mail using velocity template refer to 24.3.2 Creating email content using a velocity template library for more doc detail.

Resources