我创建了一个简单的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)
真的很感激任何帮助。
答案 0 :(得分:1)
尝试使用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();
}
}
答案 1 :(得分:1)
尝试一下,这种对邮件进行附件的方法对我有用。
MimeMesage msg=javaMailSender.createMimeMessage();
msg.addRecipient(Message.RecipientType.TO,InternetAddress(email));
msg.setSubject("Subject");
Multipart emailContent=new MimeMultipart();
MimeBodyPart textBodyPart=new MimeBodyPart();
textBodyPart.setText("My multipart");
MimeBodyPart jpgBodyPart=new MimeBodyPart();
jpgBodyPart.attachFile("C:/software/Koala.jpeg");
emailContent.addBodyPart(textBodyPart);
emailContent.addBodyPart(jpgBodyPart);
msg.setContent(emailContent);
javaMailSender.send(msg);
答案 2 :(得分:0)
除了
外,一切看起来都不错FileSystemResource res = new FileSystemResource(new File("C:/software/Koala.jpeg"));
您只需执行此操作即可将文件附加到邮件中。
helper.addAttachment("happyBirthday", new File("C:/software/Koala.jpeg"));