gpt4 book ai didi

jakarta-mail - Javamail附加多个文件

转载 作者:行者123 更新时间:2023-12-05 01:33:12 32 4
gpt4 key购买 nike

以下代码使用 javamail api 通过 gmail smtp 服务器发送邮件和附件。

    public void doSendGmail(){
from = txtFrom.getText();
password= new String(txtPassword.getPassword());
to = txtTo.getText();
cc = txtCC.getText();
bcc = txtBCC.getText();
subject = txtSubject.getText();
message_body = jtaMessage.getText();

Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");

Session session = Session.getInstance(props,null);

try {
//message definition
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
if(!cc.equals("")){
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
}
if(!bcc.equals("")){
message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc));
}
message.setSubject(subject);
if(!filename.equals("")){// if a file has been attached...
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(message_body);// actual message
Multipart multipart = new MimeMultipart();// create multipart message

// add the text message to the multipart
multipart.addBodyPart(messageBodyPart);

// attachment part
messageBodyPart = new MimeBodyPart();
String attachment = fileAbsolutePath;
DataSource source = new FileDataSource(attachment);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);//add the attachment to the multipart message
// combine text and attachment
message.setContent(multipart);
// send the complete message
Transport.send(message, from, password);
}
else{// if no file has been attached
message.setText(message_body);
Transport.send(message, from, password);
}

JOptionPane.showMessageDialog(this, "Message Sent!","Sent",JOptionPane.INFORMATION_MESSAGE);

} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.toString());
}
}

此代码一次只能附加和发送一个文件。如何使其能够附加多个文件并将它们作为一封电子邮件发送?

使用 JFileChooser 附加文​​件,如下所示:

public void doAttachFile(){
try {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File file = chooser.getSelectedFile();
filename = file.getName();// get name of selected file
lblFileName.setText(filename);// display name of selected file
fileAbsolutePath= file.getAbsolutePath();
System.out.println("File name: "+filename+"\n"+"Absolute path: "+fileAbsolutePath);

} catch (Exception e) {
JOptionPane.showMessageDialog(this, "No file was attached");
}
}

最佳答案

在附件部分使用“for”循环。

关于jakarta-mail - Javamail附加多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37847188/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com