How to send html template as mail using groovy

允我心安 提交于 2020-01-02 06:36:09

问题


I am using JavaMail API 1.4.4 to send mails. So far I am able to send the mail, but actually I need to send HTML content so that when the mail is received it processes the html tags.

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)
  }
}

回答1:


A Groovier way of sending might 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()
}



回答2:


Use setContent

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



回答3:


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



来源:https://stackoverflow.com/questions/8833892/how-to-send-html-template-as-mail-using-groovy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!