spring boot 发送邮件带附件出现Not in multipart mode - create an appropriate MimeMessageHelper错误

final MimeMessageHelper message = new MimeMessageHelper(mimeMessage);  //没带上true参数发送邮件带附件出现错误

java.lang.IllegalStateException: Not in multipart mode - create an appropriate MimeMessageHelper via a constructor that takes a 'multipart' flag if you need to set alternative texts or add inline elements or attachments.
at org.springframework.mail.javamail.MimeMessageHelper.checkMultipart(MimeMessageHelper.java:383) ~[spring-context-support-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.mail.javamail.MimeMessageHelper.getRootMimeMultipart(MimeMessageHelper.java:400) ~[spring-context-support-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.mail.javamail.MimeMessageHelper.addAttachment(MimeMessageHelper.java:998) ~[spring-context-support-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.mail.javamail.MimeMessageHelper.addAttachment(MimeMessageHelper.java:1077) ~[spring-context-support-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.mail.javamail.MimeMessageHelper.addAttachment(MimeMessageHelper.java:1047) ~[spring-context-support-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at com.example.SendEmailController.sendEmail(SendEmailController.java:37) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_71]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_71]

修改

@Controller

public class SendEmailController {
@Autowired  
JavaMailSender mailSender; 
@RequestMapping("/email")
@ResponseBody
public String sendEmail(){
try {
final MimeMessage mimeMessage = this.mailSender.createMimeMessage();  
        final MimeMessageHelper message = new MimeMessageHelper(mimeMessage,true);  //如果想要带附件 加上true    
message.setFrom("[email protected]");  
        message.setTo("[email protected]");  
        message.setSubject("测试邮件主题");  
        message.setText("有附件");
        File file =new File("F://1233.jpg");
        FileSystemResource resource =null;
        if(file.exists()){  
        System.out.println("毕业论文.doc");
        resource =new FileSystemResource(file); 
        }       
        message.addAttachment("毕业论文.jpg", resource);
         this.mailSender.send(mimeMessage);  
         } catch (MessagingException e) {
        e.getMessage();
  e.printStackTrace();
 
return "";
}
}

你可能感兴趣的:(spring-boot)