2012-01-12 68 views
4

我正在使用JavaMail API 1.4.4發送郵件。到目前爲止,我能夠發送郵件,但實際上我需要發送HTML內容,以便在收到郵件時處理html標籤。如何使用groovy將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) 
    } 
} 

回答

5

一更方便的發送方式可能是:

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

使用setContent

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

[不要忘記轉換](https://stackoverflow.com/questions/17262161/how-to-modify-the-mime-message-in-editable-email-plugin-in-jenkins/49126212# 49126212)'GString'爲'java.lang.String'。 – it3xl 2018-03-06 08:31:59

0

使用message.setText(createHtmlMessage(),「utf-8」,「html」);

相關問題