如何使用groovy将html模板作为邮件发送

时间:2012-01-12 10:55:23

标签: java groovy javamail

我正在使用JavaMail API 1.4.4发送邮件。到目前为止,我能够发送邮件,但实际上我需要发送HTML内容,以便在收到邮件时处理html标签。

示例:如果我的消息中有表格代码,则应处理html代码并将其显示在邮件中

我的代码

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

3 个答案:

答案 0 :(得分:6)

Groovier的发送方式可能是:

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

答案 1 :(得分:3)

使用setContent

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

答案 2 :(得分:0)

使用message.setText(createHtmlMessage(),“utf-8”,“html”);