首页 > 解决方案 > 带有gui的javamail多个附件

问题描述

尝试使用 GUI 做一个基本的邮件发件人应用程序,但无论我做什么都无法发送/添加多个附件(尝试了旧 Stack Overflow 问题中的大多数答案 - 没用,
我不想手动添加“multipart .addBodyPart(messageBodyPart);" 对于每个附件。有没有办法添加多个附件而无需一遍又一遍地重复代码)。我错过了什么,有什么问题?(完整的 GUI 照片作为附件添加,红字为变量名
链接 = [1]:https ://i.stack.imgur.com/KVVc9.png )

try 
        {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(FromMail));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(ToMail));
            message.setSubject(SubjectMail);
            //message.setText(ContentMail);
            
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(ContentMail);
            
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            
            messageBodyPart = new MimeBodyPart();
            
            DataSource source = new FileDataSource(AttachmentPath);
            
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(attachment_name.getText());
            
            multipart.addBodyPart(messageBodyPart);
                        
            message.setContent(multipart);
            
            Transport.send(message);
            
            JOptionPane.showMessageDialog(null, "success, message sent!");
        } 
        catch (Exception exp) 
        {
           JOptionPane.showMessageDialog(null, exp);
        }
}

private void attachmentActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        
        JFileChooser chooser = new JFileChooser();
        chooser.setMultiSelectionEnabled(true);
        
        Component frame = null;
        chooser.showOpenDialog(frame);
        
        File file = chooser.getSelectedFile();
        AttachmentPath = file.getAbsolutePath();
        
        //path_attachment.setText(AttachmentPath);
        path_attachment_area.setText(AttachmentPath);
    } 

String AttachmentPath;

标签: javaswingjakarta-mail

解决方案


这是一个最小的 GUI,有两个按钮,附加和发送,以及一个用于收集选定文件的文本区域,我没有复制你的完整 GUI,所以你必须将它集成到你的代码中。

实际上,您只需检查onAttach()正在选择附件以及onSend()for 循环将所有选定附件添加到消息的位置。

另请注意,textarea 仅用于显示选定的文件,但文件列表保存在 ArrayList 中。

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class TestEmail extends JPanel {

    String fromEmail = "myemail@mydomain.com";
    String toEmail = "destmail@anotherdomain.com";

    protected JButton attachButton=new JButton("Add attachment(s)");
    protected JButton sendButton=new JButton("Send");
    protected JTextArea attachmentsArea=new JTextArea(10, 30);
    protected JFileChooser chooser=new JFileChooser();
    
    protected List<File> attachments=new ArrayList<File>();

    public TestEmail() {
        setLayout(new BorderLayout());

        attachmentsArea.setEditable(false);
        chooser.setMultiSelectionEnabled(true);

        JScrollPane scrollPane=new JScrollPane(attachmentsArea);
        add(scrollPane,BorderLayout.CENTER);
        
        Box buttonPanel=new Box(BoxLayout.X_AXIS);
        buttonPanel.add(Box.createHorizontalGlue());
        buttonPanel.add(attachButton);
        buttonPanel.add(sendButton);
        
        add(buttonPanel,BorderLayout.SOUTH);
        attachButton.addActionListener((e)->onAttach());
        sendButton.addActionListener((e)->onSend());
    }

    public Session getSession() {
        final String password = "mypassword";
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.mydomain.com"); // SMTP Host
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.auth", "true"); // enable authentication
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");  
        Authenticator auth = new Authenticator() {
            // override the getPasswordAuthentication method
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(fromEmail, password);
            }
        };

        return Session.getInstance(props, auth);
    }

    public void onAttach() {
        if (chooser.showOpenDialog(this)==JFileChooser.APPROVE_OPTION) {
            for (File f: chooser.getSelectedFiles()) {
                if (!f.isDirectory()&&!attachments.contains(f)) {
                    attachments.add(f);
                    attachmentsArea.append(f.getAbsolutePath()+"\n");
                }
            }
        }
    }
    
    public void onSend() {
        try {
            Session session = getSession();
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(fromEmail));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
            message.setSubject("A subject");
    
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText("Dummy message, just to send attachments.");
    
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
    
            for (File f: attachments) {
                MimeBodyPart part=new MimeBodyPart();
                part.attachFile(f);
                multipart.addBodyPart(part);
            }
            message.setContent(multipart);
            Transport.send(message);
            JOptionPane.showMessageDialog(this, "Message successfully sent", "Success", JOptionPane.INFORMATION_MESSAGE);
        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "Exception sending e-mail:\n"+ex.getMessage(),"Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    public static void main(String[] args) {
        EventQueue.invokeLater(()->{
            JFrame frame=new JFrame("Sendmail");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(new TestEmail());
            frame.pack();
            frame.setVisible(true);
        });
    }
}

推荐阅读