有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

带有gui的java javamail多附件

尝试用GUI做一个基本的邮件发送者应用程序,但无论我做什么都无法发送/添加多个 附件(在旧的堆栈溢出问题中尝试了大多数答案-不起作用,
我不想手动添加“multipart.addBodyPart(messageBodyPart);”每一个附件。有没有一种方法可以添加多个附件,而无需重复代码)。我错过了什么,怎么了?(完整的GUI照片作为附件添加,红色文字是可变名称
link=[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;

共 (1) 个答案

  1. # 1 楼答案

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

    实际上,您只需选中onAttach()选择附件,以及onSend()for循环将所有选择的附件添加到消息中

    还要注意,文本区域仅用于显示所选文件,但文件列表保存在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);
            });
        }
    }