Java Mail Mailgun GUI 项目附加图像而不是嵌入图像

问题描述 投票:0回答:1

这是我第一次用 Java 编写一些东西,所以我慢慢地学习,但我很难解决如何解决这个问题。我在获取用户插入到我的 JEditorPane editerPane 中的图像以作为嵌入图像而不是电子邮件中的文件附件发送时遇到问题。

    private static void embedAndSendEmail(JEditorPane editorPane) throws IOException, BadLocationException, URISyntaxException {
        HTMLDocument doc = (HTMLDocument) editorPane.getDocument();
        ElementIterator iterator = new ElementIterator(doc);
        Element element;

            // Collect images to embed
            List<File> imageFiles = new ArrayList<>();
            while ((element = iterator.next()) != null) {
                AttributeSet attrs = element.getAttributes();
                Object nameAttr = attrs.getAttribute(StyleConstants.NameAttribute);

                if (nameAttr instanceof HTML.Tag) {
                    HTML.Tag tag = (HTML.Tag) nameAttr;

                    if (tag == HTML.Tag.IMG) {
                        String src = (String) attrs.getAttribute(HTML.Attribute.SRC);
                        if (src != null && src.startsWith("file:///")) {
                            // Read image data from editor pane
                            InputStream inputStream = new URL(src).openStream();
                            byte[] imageData = inputStream.readAllBytes();
                            String base64Image = Base64.getEncoder().encodeToString(imageData);

                            // Replace src attribute with base64 data
                            String newSrc = "data:image/png;base64," + base64Image;
                            doc.setInnerHTML(element, "<img src=\"" + newSrc + "\">");

                            // Add image file to the list (for sending email later)
                            String filePath = new URI(src).getPath(); // Convert URL to file path
                            imageFiles.add(new File(filePath));
                        }
                    }
                }
            }

    }

我尝试走 Base64 路线,尽管我知道它不如使用 Mimebodypart() 可靠,但我正在尝试发送用户插入的图像。

下面我放置了相互交互的代码,以发送电子邮件(减去面板和按钮)。下面的代码尝试嵌入这些图像,但与作为附件发送的结果相同。

public class testing {
    private static void createAndShowGUI() {
        JFrame frame = new JFrame("Mailgun");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(1280, 720);
        
        
        //Listener to insert an image upon clicking
        imageInsert.addActionListener(e -> {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileFilter(new FileNameExtensionFilter("Images", "jpg", "jpeg", "png", "gif"));
            if (fileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
                File imageFile = fileChooser.getSelectedFile();
                insertImage(editorPane, imageFile);
            }
        });
        
        JButton sendButton = new JButton("Send Email");
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String to = emailField.getText();
                String subject = subjectField.getText();
                String content = "<html><body>"                
                        + editorPane.getText()
                        +"</body></html>";
                //Made to not allow an email to be sent till fields are not empty
                if (to.isEmpty() || subject.isEmpty() || content.isEmpty()) {
                    JOptionPane.showMessageDialog(frame, "Please fill in all fields.");
                    return;
                }

                try {
                    sendEmail(to, subject, content, imageFiles);
                } catch (IOException | MessagingException e1) {
                    e1.printStackTrace();
                }
            }
        

}
        private static void sendEmail(String to, String subject, String content, List<File> imageFiles) throws IOException, MessagingException {
            final String username = "";
            final   String password = "";
            Properties properties = new Properties();
            properties.put("mail.smtp.auth", "true");
            properties.put("mail.smtp.starttls.enable", "true");
            properties.put("mail.smtp.host", "smtp.mailgun.com");
            properties.put("mail.smtp.port", "587");

            Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
            MimeMultipart multipart = new MimeMultipart("related");
            

            try {
                for (File imageFile : imageFiles) {
                    MimeBodyPart imagePart = new MimeBodyPart();
                    DataSource ds = new FileDataSource(imageFile);
                    imagePart.setDataHandler(new DataHandler(ds));
                    imagePart.setHeader("Content-ID", "<image>");
                    imagePart.setDisposition(MimeBodyPart.INLINE);
                    imagePart.setFileName(imageFile.getName());
                    multipart.addBodyPart(imagePart);
                }
                

                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(username));
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
                message.setSubject(subject);
                


                // Set the content of the message to the multipart
                message.setContent(multipart);

                // Send message
                Transport.send(message);
                JOptionPane.showMessageDialog(null, "Email sent successfully.");
            } catch (MessagingException e) {
                JOptionPane.showMessageDialog(null, "Failed to send email: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }

真的不知道从这里该去哪里,非常感谢任何建议!

java swing email mailgun
1个回答
0
投票

这只是一个概念证明。

测试.java

package com.example.mail;

import jakarta.mail.Session;
import jakarta.activation.DataHandler;
import jakarta.activation.DataSource;
import jakarta.activation.FileDataSource;
import jakarta.mail.BodyPart;
import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeBodyPart;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMultipart;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.io.IOException;

public class Test {
    public static void main(String[] args) throws MessagingException, IOException {
        String to =  "[email protected]";
        String subject1 = "Testing Subject1";
        String subject2 = "Testing Subject2";
        /*
        String content = "<html><body>"
                + "<h1>Hello</h1>"
                +"</body></html>";
         */
        String content = "<html><body>"
                + "<H1>Hello</H1>"
                + "<img src=\"cid:image1\"><p/>"
                + "<H1>Hello2</H1>"
                + "<img src=\"cid:image2\"><p/>"
                +"</body></html>";

        List<File> imageFiles =new ArrayList<File>();
        imageFiles.add(new File("/home/demo/Documents/Examples_JakartaEE/JakartaMail/src/main/resources/icon01.png"));
        imageFiles.add(new File("/home/demo/Documents/Examples_JakartaEE/JakartaMail/src/main/resources/icon02.png"));

        sendEmail(to, subject1, content, imageFiles);
        sendEmail2(to, subject2, content, imageFiles);

    }

    public static void sendEmail2(String to, String subject, String content, List<File> imageFiles) throws IOException, MessagingException {
        final String username = "[email protected]";
        final String password = "1234";

        String host = "smtp.james.local";  //smtp.mailgun.com
        Properties properties = new Properties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", "587");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.ssl.trust", host);

        Session session = Session.getInstance(properties, new jakarta.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        MimeMultipart multipart = new MimeMultipart("related");
        // first part (the html)
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content, "text/html");
        // add it
        multipart.addBodyPart(messageBodyPart);

        int imageCount =0;
        try {
            for (File imageFile : imageFiles) {
                imageCount++;
                //MimeBodyPart imagePart = new MimeBodyPart();
                BodyPart imagePart = new MimeBodyPart();
                DataSource ds = new FileDataSource(imageFile);
                imagePart.setDataHandler(new DataHandler(ds));
                imagePart.setHeader("Content-ID", "<image"+ imageCount+">");
                //imagePart.setDisposition(MimeBodyPart.INLINE);
                //imagePart.setFileName(imageFile.getName());
                multipart.addBodyPart(imagePart);
            }

            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject);

            // Set the content of the message to the multipart
            message.setContent(multipart);

            // Send message
            Transport.send(message);
            //JOptionPane.showMessageDialog(null, "Email sent successfully.");
        } catch (MessagingException e) {
            //JOptionPane.showMessageDialog(null, "Failed to send email: " + e.getMessage());
            e.printStackTrace();
        }
    }


   public static void sendEmail(String to, String subject, String content, List<File> imageFiles) throws IOException, MessagingException {
       final String username = "[email protected]";
       final String password = "1234";

       String host = "smtp.james.local";  //smtp.mailgun.com
       Properties properties = new Properties();
       properties.put("mail.smtp.auth", "true");
       properties.put("mail.smtp.starttls.enable", "true");
       properties.put("mail.smtp.host", host);
       properties.put("mail.smtp.port", "587");
       properties.put("mail.smtp.ssl.trust", host);


        Session session = Session.getInstance(properties, new jakarta.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        MimeMultipart multipart = new MimeMultipart("related");


        try {
            for (File imageFile : imageFiles) {
                MimeBodyPart imagePart = new MimeBodyPart();
                DataSource ds = new FileDataSource(imageFile);
                imagePart.setDataHandler(new DataHandler(ds));
                imagePart.setHeader("Content-ID", "<image>");
                imagePart.setDisposition(MimeBodyPart.INLINE);
                imagePart.setFileName(imageFile.getName());
                multipart.addBodyPart(imagePart);
            }


            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject);



            // Set the content of the message to the multipart
            message.setContent(multipart);

            // Send message
            Transport.send(message);
            //JOptionPane.showMessageDialog(null, "Email sent successfully.");
        } catch (MessagingException e) {
            //JOptionPane.showMessageDialog(null, "Failed to send email: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

没有GUI代码,只有简单的硬代码用于测试。

  • (1) sendEmail 是您的版本
  • (2)sendEmail2是修改后的版本。

需要使用 cid 将图像添加到内容中。

注意:要在内容中嵌入图像,请使用

<img src="cid:image1">
,其中 cid 的名称必须与后续图像的名称相同(image1、image2、...)

修改项目1:

//MimeBodyPart imagePart = new MimeBodyPart();

BodyPart imagePart = new MimeBodyPart();

修改项目2:

//imagePart.setHeader("Content-ID", "<image>");

imagePart.setHeader("Content-ID", "<image"+ imageCount+">");

修改项3:删除两个。

//imagePart.setDisposition(MimeBodyPart.INLINE);
                //imagePart.setFileName(imageFile.getName());

sendmail - 内容中仅显示一张图像,邮件中将出现两个附件文件。

enter image description here

sendmail2 - 内容中显示2张图片,邮件中不出现附件文件。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.