如何发送带有附件JavaMail的电子邮件

时间:2019-01-27 15:58:24

标签: javamail email-attachments

我正在尝试通过javamail发送带有附件的电子邮件。 我的代码:

   @Override
public boolean sendMessage(long id, String mailContent, Optional<MultipartFile> file) {
    Client client = clientService.get(id);
    String userName = SecurityContextHolder.getContext().getAuthentication().getName();
    logger.info("Sending email to " + client.getFullName() + " , sender " + userName);

    String mailSendTo = client.getEmail();

    String mailServerSmtpHost = environment.getRequiredProperty("spring.mail.host");
    String mailSmtpAuth = environment.getRequiredProperty("spring.mail.properties.mail.smtp.auth");
    String starttlsEnable = environment.getRequiredProperty("spring.mail.properties.mail.smtp.starttls.enable");
    String SMTPport = environment.getRequiredProperty("spring.mail.properties.mail.smtp.port");

    Properties property = System.getProperties();
    property.setProperty("mail.smtp.host", mailServerSmtpHost);
    property.setProperty("mail.smtp.port", SMTPport);
    property.setProperty("mail.smtp.auth", mailSmtpAuth);
    property.setProperty("mail.smtp.starttls.enable", starttlsEnable);

    Authenticator authenticator = new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(sendMailFrom, mailPassword);
        }
    };
    Session session = Session.getInstance(property, authenticator);
    try{
        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setHeader("Content-type", "text/HTML; charset=UTF-8");
        mimeMessage.setHeader("format", "flowed");
        mimeMessage.setHeader("Content-Transfer-Encoding", "8bit");
        mimeMessage.setFrom(new InternetAddress(sendMailFrom));
        mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailSendTo));
        mimeMessage.setSubject("hi");

        MimeBodyPart content = new MimeBodyPart();
        content.setText(removeHTMLtags(mailContent));

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(content);

        if (file.isPresent()){
            MultipartFile multipartFile = file.get();
            BodyPart bodyPart = new MimeBodyPart();
            String filePath = **"hardcodedPath"** + multipartFile.getOriginalFilename();
            DataSource dataSource = new FileDataSource(filePath);
            bodyPart.setDataHandler(new DataHandler(dataSource));
            bodyPart.setFileName(multipartFile.getOriginalFilename());
            multipart.addBodyPart(bodyPart);
        }
        mimeMessage.setContent(multipart);
        Transport.send(mimeMessage);
        return true;
    } catch (AddressException e) {

    } catch (MessagingException e) {

    }
    return false;
}

一切正常,除了我需要获取不是硬编码而是在运行时获取的附件的绝对路径。 据我所知,JS无法为我提供。有谁知道在这种情况下如何获得依恋的绝对路径?

2 个答案:

答案 0 :(得分:0)

我通过公交文件夹解决了这个问题

 private String downloadFile(MultipartFile file){
    String localPath = environment.getRequiredProperty("email.localfolder.send.attachment")
                                                        + file.getOriginalFilename();
    File f = new File(localPath);
    try {
        OutputStream outputStream = new FileOutputStream(f);
        outputStream.write(file.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return localPath;
}

然后替换

String filePath = **"hardcodedPath"** + multipartFile.getOriginalFilename();

String filePath = downloadFile(multipartFile);

其余-不变

希望这会帮助任何人。

答案 1 :(得分:0)

您无需将附件存储为实际文件。 如果内存中有附件的字节,则可以直接将其附加:

        MultipartFile multipartFile = file.get();
        BodyPart bodyPart = new MimeBodyPart();
        // choose MIME type based on file name
        String mimeType = FileTypeMap.getDefaultFileTypeMap().getContentType(multipartFile.getOriginalFilename());
        DataSource dataSource = new ByteArrayDataSource(multipartFile.getBytes(), mimeType);
        bodyPart.setDataHandler(new DataHandler(dataSource));
        bodyPart.setFileName(multipartFile.getOriginalFilename());
        bodyPart.setDisposition(Part.ATTACHMENT);
        multipart.addBodyPart(bodyPart);