2017-04-24 56 views
0

我想发送下面提到的结果给电子邮件,并希望通过电子邮件仔细收到它们。因此我决定使用html代码,但没有结果。如何发送java电子邮件类中的HTML标记?

caputure.png图像Result what i receive:

代码:

公共静态无效sendresult(ShowResultModel showuserresulttable){

final String username = ***** 
    final String password = ******; 

    Properties props = new Properties(); 
    props.put("mail.smtp.auth", "true"); 
    props.put("mail.smtp.starttls.enable", "true"); 
    props.put("mail.smtp.host", "smtp.gmail.com"); 
    props.put("mail.smtp.port", "587"); 

    Session session = Session.getInstance(props, 
      new javax.mail.Authenticator() { 
       protected PasswordAuthentication getPasswordAuthentication() { 
        return new PasswordAuthentication(username, password); 
       } 
      }); 

    try { 

     Message message = new MimeMessage(session); 
     message.setFrom(new InternetAddress("[email protected]")); 
     message.setRecipients(Message.RecipientType.TO, 
       InternetAddress.parse("[email protected]")); 

     message.setSubject("Exammer result :" + showuserresulttable.getUsername()); 

     DecimalFormat formatter = new DecimalFormat("#0.00"); 

     String MESSAGE = " "; 
     double resultpercent = showuserresulttable.getScore() /(double) showuserresulttable.getTotalanswer()*100; 

     MESSAGE+="<b>Username:</b> " + showuserresulttable.getUsername() + "<br><hr>"; 
     MESSAGE+="<b>Subject</b>" + showuserresulttable.getSubject() + "<br><hr>"; 
     MESSAGE+="<b>Variant :</b>" + showuserresulttable.getVariant() + "<br><hr>"; 
     MESSAGE+="<b>Score of result:</b>" + showuserresulttable.getScore() + "<br><hr>"; 
     MESSAGE+="<b>Total question :</b>" + showuserresulttable.getTotalanswer()+ "<br><hr>"; 
     MESSAGE+="<b> Score percent:</b>" + resultpercent + "<br><hr>"; 
     MESSAGE+="<b>Spendtime:</b>" + showuserresulttable.getSpendtime() + "second" + "<br><hr>"; 
     MESSAGE+="<b>Examdate:</b>" + showuserresulttable.getExamdate() ; 

     message.setText(MESSAGE); 
     Transport.send(message); 

     System.out.println("Mail gonderildi!"); 
    } catch (MessagingException e) { 
     throw new RuntimeException(e); 
    } 

} 
+1

可能的重复[我如何发送HTML电子邮件?](http://stackoverflow.com/questions/5068827/how-do-i-send-an-html-email) –

回答

2

message.setText(MESSAGE);,而不是你应该使用message.setText(MESSAGE, true);here true是代表html(是否申请HTML邮件的内容类型“text/html”,使用默认内容类型(“text/plain”)else)

另外,如果你使用的是thymeleaf或freemarker,那么你可以在那里使用模板。

+0

我尝试你什么的建议,但是当我在课堂上写出真正的红色下划线错误时,“设置文本字符串部分无法应用”,该怎么办? –

+0

你使用spring javacv邮件依赖关系吗? –

+0

我不使用弹簧。我已经在ide intellejis编码,导入下面提到的罐子:import java.text.DecimalFormat; import java.util.List; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; –