使用 Spring 和 JavaMail 发送组合的纯文本/HTML 邮件

发布于 2024-12-05 14:36:27 字数 1009 浏览 3 评论 0原文

我目前正在使用 JavaMail 和 Spring 以 HTML 格式发送电子邮件。碰巧,HTML 是由我拥有的一些 Velocity 模板生成的,发送代码大致如下:

MimeMessagePreparator preparator = new MimeMessagePreparator() {

    @Override public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");

            message.setSubject(msgInfo.getSubject());
            message.setFrom(msgInfo.getFrom());
            message.setReplyTo(msgInfo.getFrom());
            message.setTo(address);
            message.setText(someText, true);
    }
}

mailSender.send(preparator);

这工作得很好,但它只发送一个部分为 text/html 的邮件。我需要的是用纯文本部分以多部分替代方式发送它。有没有办法使用 Spring 和 JavaMail 自动执行此操作?


PS

在以前的生活中,当我使用 Visual Basic 和 CDONTS 进行编程时,这是内置的,但是我似乎无法找到一种简单的方法来使用 Java 来做到这一点。纯文本版本是否好看并不重要,它必须存在即可。我试图避免的是必须为此维护整个第二组 Velocity 模板。

I'm currently using JavaMail and Spring to send email in HTML. As it happens, the HTML is generated by some Velocity templates I have, and the sending code is roughly as follows:

MimeMessagePreparator preparator = new MimeMessagePreparator() {

    @Override public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");

            message.setSubject(msgInfo.getSubject());
            message.setFrom(msgInfo.getFrom());
            message.setReplyTo(msgInfo.getFrom());
            message.setTo(address);
            message.setText(someText, true);
    }
}

mailSender.send(preparator);

This works just fine, but it sends the mail with only a single part as text/html. What I need is to send it in multipart alternative with a plain text part. Is there a way, using Spring and JavaMail, to do this in an automatic way?


P.S.

In a former life when I programmed with Visual Basic and CDONTS this was built-in, but I can't seem to find a simple way to do it with Java. It's not terribly important that the plain text version look good, it just has to exist. What I'm trying to avoid is having to maintain a whole second set of Velocity templates just for this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

盛夏已如深秋| 2024-12-12 14:36:27

为了发送文本和 HTML 部分,您需要使用不同的 setText() 方法:

public void setText(String plainText, String htmlText)

如果您将纯文本设置为您的 HTML 内容,您可能需要解析 HTML 以删除 HTML 标签。

In order to send both Text and HTML parts, you need to use a different setText() method:

public void setText(String plainText, String htmlText)

If you are setting the plain text to your HTML content, you may need to parse the HTML to remove the HTML tags.

草莓味的萝莉 2024-12-12 14:36:27
try {

    // Email data
    String Email_Id = "[email protected]"; // change to your
                                                    // email ID
    String password = "Your PSWD"; // change to your password
    String recipient_mail_id = "[email protected]"; // change to
                                                            // recipient
                                                            // email id
    String mail_subject = "Attendance Report";

    // Set mail properties
    Properties props = System.getProperties();
    String host_name = "smtp.gmail.com";
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host_name);
    props.put("mail.smtp.user", Email_Id);
    props.put("mail.smtp.password", password);
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.auth", "true");

    Session session = Session.getDefaultInstance(props);
    MimeMessage message = new MimeMessage(session);

    try {
        // Set email data
        message.setFrom(new InternetAddress(Email_Id));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient_mail_id));
        message.setSubject(mail_subject);
        MimeMultipart multipart = new MimeMultipart();
        BodyPart messageBodyPart = new MimeBodyPart();

        // Set key values
        Map<String, String> input = new HashMap<String, String>();
        input.put("User", name.toString());
        input.put("Date", date1);
        input.put("Content In", "English");
        input.put("Absent", absentUser);

        // HTML mail content
        // String htmlText =
        // readEmailFromHtml("/home/techwalnut-pc/mailTemplate.html",
        // input);
        String htmlText = readEmailFromHtml(
                "/home/techwalnut-pc/Development/Aniket/Techwalnut/Project/Java/Spring/Attendance_system/mailTemplate.html",
                input);
        messageBodyPart.setContent(htmlText, "text/html");

        multipart.addBodyPart(messageBodyPart);
        message.setContent(multipart);

        // Conect to smtp server and send Email
        Transport transport = session.getTransport("smtp");
        transport.connect(host_name, Email_Id, password);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        System.out.println("Mail sent successfully...");

    } catch (MessagingException ex) {
    } catch (Exception ae) {
        ae.printStackTrace();
    }
} catch (Exception exception) {
   exception.printStackTrace();
}
try {

    // Email data
    String Email_Id = "[email protected]"; // change to your
                                                    // email ID
    String password = "Your PSWD"; // change to your password
    String recipient_mail_id = "[email protected]"; // change to
                                                            // recipient
                                                            // email id
    String mail_subject = "Attendance Report";

    // Set mail properties
    Properties props = System.getProperties();
    String host_name = "smtp.gmail.com";
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host_name);
    props.put("mail.smtp.user", Email_Id);
    props.put("mail.smtp.password", password);
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.auth", "true");

    Session session = Session.getDefaultInstance(props);
    MimeMessage message = new MimeMessage(session);

    try {
        // Set email data
        message.setFrom(new InternetAddress(Email_Id));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient_mail_id));
        message.setSubject(mail_subject);
        MimeMultipart multipart = new MimeMultipart();
        BodyPart messageBodyPart = new MimeBodyPart();

        // Set key values
        Map<String, String> input = new HashMap<String, String>();
        input.put("User", name.toString());
        input.put("Date", date1);
        input.put("Content In", "English");
        input.put("Absent", absentUser);

        // HTML mail content
        // String htmlText =
        // readEmailFromHtml("/home/techwalnut-pc/mailTemplate.html",
        // input);
        String htmlText = readEmailFromHtml(
                "/home/techwalnut-pc/Development/Aniket/Techwalnut/Project/Java/Spring/Attendance_system/mailTemplate.html",
                input);
        messageBodyPart.setContent(htmlText, "text/html");

        multipart.addBodyPart(messageBodyPart);
        message.setContent(multipart);

        // Conect to smtp server and send Email
        Transport transport = session.getTransport("smtp");
        transport.connect(host_name, Email_Id, password);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        System.out.println("Mail sent successfully...");

    } catch (MessagingException ex) {
    } catch (Exception ae) {
        ae.printStackTrace();
    }
} catch (Exception exception) {
   exception.printStackTrace();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文