gpt4 book ai didi

java - 如何使用 JavaMail 将多个文件附加到电子邮件?

转载 作者:IT老高 更新时间:2023-10-28 21:00:11 25 4
gpt4 key购买 nike

以下 Java 代码用于将文件附加到电子邮件。我想通过电子邮件发送 多个 文件附件。任何建议将不胜感激。

public class SendMail {

public SendMail() throws MessagingException {
String host = "smtp.gmail.com";
String Password = "mnmnn";
String from = "xyz@gmail.com";
String toAddress = "abc@gmail.com";
String filename = "C:/Users/hp/Desktop/Write.txt";
// Get system properties
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtps.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props, null);

MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, toAddress);
message.setSubject("JavaMail Attachment");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Here's the file");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);

try {
Transport tr = session.getTransport("smtps");
tr.connect(host, from, Password);
tr.sendMessage(message, message.getAllRecipients());
System.out.println("Mail Sent Successfully");
tr.close();
} catch (SendFailedException sfe) {
System.out.println(sfe);
}
}
}`

最佳答案

好吧,我已经有一段时间没有完成 JavaMail 工作了,但看起来你可以多次重复这段代码:

DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);

例如,您可以编写一个方法来做到这一点:

private static void addAttachment(Multipart multipart, String filename)
{
DataSource source = new FileDataSource(filename);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
}

然后从您的主代码中调用:

addAttachment(multipart, "file1.txt");
addAttachment(multipart, "file2.txt");

关于java - 如何使用 JavaMail 将多个文件附加到电子邮件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3177616/

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