gpt4 book ai didi

java - 使用 Spring JavaMailSender 将文件作为附件或内联发送

转载 作者:行者123 更新时间:2023-11-30 02:58:32 32 4
gpt4 key购买 nike

我创建了一个简单的 spring 应用程序,它向用户发送电子邮件。这似乎与“SimpleMailMessage”完美配合(整个消息都是纯文本)。我想要的是将一些文件作为附件发送,所以我尝试使用 javax.mail.internet.MimeMessage 但收到一些我无法追踪的有线错误。下面是我的片段

try {
javax.mail.internet.MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message,true);
helper.setTo(employee.getEmailId());
helper.setFrom("abc@xyz.com");
helper.setText(mailMessage, true);
helper.setSubject(subject);
FileSystemResource res = new FileSystemResource(new File("C:/software/Koala.jpeg"));
helper.addAttachment("happyBirthday", res);
mailSender.send(message);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

错误是:

Caused by: java.lang.LinkageError: loader constraint violation: when resolving method "javax.mail.internet.MimeBodyPart.setDataHandler(Ljavax/activation/DataHandler;)V" the class loader (instance of org/jboss/classloader/spi/base/BaseClassLoader) of the current class, org/springframework/mail/javamail/MimeMessageHelper, and the class loader (instance of org/jboss/classloader/spi/base/BaseClassLoader) for resolved class, javax/mail/internet/MimeBodyPart, have different Class objects for the type n/DataHandler;)V used in the signature
at org.springframework.mail.javamail.MimeMessageHelper.addAttachment(MimeMessageHelper.java:997)
at org.springframework.mail.javamail.MimeMessageHelper.addAttachment(MimeMessageHelper.java:1077)
at org.springframework.mail.javamail.MimeMessageHelper.addAttachment(MimeMessageHelper.java:1047)
at Example1.sendEmail(Example1.java:89)

任何帮助将不胜感激。

最佳答案

尝试使用 Byte[] 类型,您必须使用以下代码将文件转换为 Byte[] :

Path path = Paths.get("path/to/file");
byte[] content = Files.readAllBytes(path);

当您准备好发送邮件时调用此函数:

public void sendEmail(String to,String from,String sub,String msgBody,byte[] content){

MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(sub);
helper.setText(msgBody);
helper.addAttachment("MyTestFile.txt", new ByteArrayResource(content));
mailSender.send(message);
} catch (MessagingException e) {

e.printStackTrace();
}
}

关于java - 使用 Spring JavaMailSender 将文件作为附件或内联发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36552918/

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