Java Mail API setContent()不是作为HTML写在邮件正文中的

Anu*_*mal 6 java jakarta-mail

我需要在邮件正文中添加一些HTML内容.这是我到目前为止所尝试的.

            message.setContent(
                      "<h1>You Have a Promotion</h1>",
                     "text/html");

            message.setContent(
                      "<h3>Your First Name :</h3>" + FirstNm,
                     "text/html");

            message.setContent(
                      "<h3>Your Last Name :</h3>" + LastNm,
                     "text/html");

            message.setContent(
                      "<h5>Your Employee ID :</h5>" + Employeeid,
                     "text/html");
Run Code Online (Sandbox Code Playgroud)

如果我得到Out,则只将最后一个字段显示在邮件正文中,即员工ID.我想在邮件正文中显示所有三个字段.谢谢.

vin*_*bra 7

如果多次调用方法的内容,它只会设置一次,它将覆盖以前的值.

试试这个 :-

message.setContent(
                      "<h1>You Have a Promotion</h1> <h3>Your First Name :</h3>" + FirstNm + 
                      "<h3>Your Last Name :</h3>" + LastNm + "<h5>Your Employee ID :</h5>" + Employeeid ,
                     "text/html");
Run Code Online (Sandbox Code Playgroud)

下面是在多部分消息的情况下设置文本的代码

BodyPart messageBodyPart = new MimeBodyPart();
                // Fill the message
                messageBodyPart.setContent("<h1>You Have a Promotion</h1> <h3>Your First Name :</h3>" + FirstNm + 
                          "<h3>Your Last Name :</h3>" + LastNm + "<h5>Your Employee ID :</h5>" + Employeeid ,"text/html");
                // Create a multipar message
                Multipart multipart = new MimeMultipart();
                // Set text message part
                multipart.addBodyPart(messageBodyPart);

                // Part two is attachment
                messageBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource("");//add file path
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName("");//file name to be displayed
                multipart.addBodyPart(messageBodyPart);
                message.setContent(multipart);
Run Code Online (Sandbox Code Playgroud)