[英]javamail multiple attachment with gui
嘗試使用 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;
這是一個最小的 GUI,有兩個按鈕,附加和發送,以及一個用於收集選定文件的文本區域,我沒有復制你的完整 GUI,所以你必須將它集成到你的代碼中。
實際上,您只需檢查正在選擇附件的 onAttach( 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);
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.