How to send html template as mail using groovy

I am using JavaMail API 1.4.4 to send emails. While I can send mail, but in fact I need to send HTML content so that html tags are processed when receiving mail.

Example: if I have a table code in my message, it should process the html code and present it in the mail

My code

import java.io.File; import java.util.* import javax.mail.* import javax.mail.internet.* import javax.activation.* class Mail { static void sendMail(mailProp) { // Get system properties Properties properties = System.getProperties() // Setup mail server properties.setProperty("mail.smtp.host", mailProp.host) // Get the default Session object. Session session = Session.getDefaultInstance(properties) try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session) // Set From: header field of the header. message.setFrom(new InternetAddress(mailProp.from)) // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO,new InternetAddress(mailProp.to)) // Set Subject: header field message.setSubject("My Subject!") // Now set the actual message message.setText(createMessage()) // Send message Transport.send(message) System.out.println("Sent message successfully....") } catch( MessagingException mex ) { mex.printStackTrace() } } static def createMessage() { def message="""<h1>This is actual message</h1>""" } static main(args) { AppProperties.load() def mailProp=[:] mailProp.host=AppProperties.get("host") mailProp.from=AppProperties.get("sender") mailProp.to=AppProperties.get("receiver") mailProp.server=AppProperties.get("mailserver") sendMail(mailProp) } } 
+4
source share
3 answers

Groovier shipping method could be:

 try { // Create a default MimeMessage object. new MimeMessage(session).with { message -> // From, Subject and Content from = new InternetAddress( mailProp.from ) subject = "My Subject!" setContent createMessage(), 'text/html' // Add recipients addRecipient( Message.RecipientType.TO, new InternetAddress( mailProp.to ) ) // Send the message Transport.send( message ) println "Sent successfully" } } catch( MessagingException mex ) { mex.printStackTrace() } 
+6
source

Use setContent

 message.setContent("<h1>This is actual message</h1>", "text/html") 
+4
source

Use message.setText (createHtmlMessage (), "utf-8", "html");

0
source

Source: https://habr.com/ru/post/1390618/


All Articles