我的Java REST Web应用程序中有以下Spring代码:

码:

@Service("Mailer")
public class Mailer {

    private final JavaMailSender mailSender;

    private void send(final Email email){

        MimeMessage mimeMessage = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        helper.setFrom(address);
        helper.setTo(email.to());
        helper.setSubject(email.subject());

        helper.setText(email.content(), true); //is this correct?

        mailSender.send(mimeMessage);

    }

}


MimeMessageHelper setText():

public void setText(String text, boolean html) throws MessagingException {
        Assert.notNull(text, "Text must not be null");
        MimePart partToUse;
        if (isMultipart()) {
            partToUse = getMainPart();
        }
        else {
            partToUse = this.mimeMessage;
        }
        if (html) {
            setHtmlTextToMimePart(partToUse, text);
        }
        else {
            setPlainTextToMimePart(partToUse, text);
        }
    }


我的代码按预期方式发送了一封电子邮件,但是当我收到时-它是痛苦的文字。

HTML不会在电子邮件正文中呈现,并且电子邮件开头为:

<!DOCTYPE html>
<html lang="en">
   <head>
...


如何确保电子邮件以HTML而不是纯文本格式发送和呈现?

最佳答案

尝试像这样直接设置MimeMessage内容。

mimeMessage.setContent(email.content(), "text/html");
mimeMessage.saveChanges();

10-07 14:20