我卡住了,无法解决发送带有附件的电子邮件的问题。

没有附件,一切正常。当我尝试添加附件时,出现异常:

Failed messages: javax.mail.MessagingException: IOException while sending message;nested exception is:
java.io.IOException: javax.mail.MessagingException: Empty multipart: multipart/related;
boundary="----=_Part_1_733213598.1441009036818"

这是我的属性文件:
[email protected]
spring.mail.host=smtp.gmail.com
spring.mail.port=587
[email protected]
spring.mail.password=****
spring.mail.properties.mail.mime.multipart.allowempty=true
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.ssl.trust=smtp.gmail.com

和使用它的类:
@Component
public class MailSenderService {

    @Autowired
    JavaMailSender javaMailSender;

    @Value("${reports.mailSender.clientEmail}")
    private String clientEmail;

    public void sendMessage() {

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        FileSystemResource file = new FileSystemResource(new File("c:\\simple.jpg"));
        try {
            mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(clientEmail));
            mimeMessage.setFrom("[email protected]");
            mimeMessage.setText(
                    "Hi");
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.addAttachment(file.getFilename(), file);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

        try {
            this.javaMailSender.send(mimeMessage);
        } catch (MailException ex) {
            // simply log it and go on...
            System.err.println(ex.getMessage());
        }
    }
}

猜测MimeMessageHelper存在问题,但无法单独解决。任何人都可以尝试帮助我吗?

最佳答案

该错误是由于您

@Jen在他的评论中是正确的,您正在错误地设置邮件的文本。
您的代码中有错误,请按如下所示进行更改,然后尝试:-

MimeMessage mimeMessage = javaMailSender.createMimeMessage();
FileSystemResource file = new FileSystemResource(new File("c:\\simple.jpg"));
try {
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.addRecipient(Message.RecipientType.TO, new InternetAddress(clientEmail));
    helper.setFrom("[email protected]");
    helper.setText("Hi");
    helper.addAttachment(file.getFilename(), file);
} catch (MessagingException e) {
    e.printStackTrace();
}

try {
    this.javaMailSender.send(mimeMessage);
} catch (MailException ex) {
    // simply log it and go on...
    System.err.println(ex.getMessage());
}

关于java - 发送带有附件的电子邮件-多部分为空,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32306928/

10-11 10:32