Иван
Иван

Reputation: 13

How to send email with attachment JavaMail

I'm trying to sent email with attachment through javamail. My code:

   @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;
}

all works fine except that I need to get absolute path of attachment not hardcoded but obtained at runtime. JS cant provide me with it as far as I know. Does anyone know how to get the absolute path of attachment in this situation?

Upvotes: 1

Views: 1256

Answers (2)

Bill Shannon
Bill Shannon

Reputation: 29971

You never need to store the attachment as an actual file. If you have the bytes for the attachment in memory, you can attach them directly:

        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);

Upvotes: 2

Иван
Иван

Reputation: 13

I solved the issue through transit folder

 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;
}

then replace

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

with

String filePath = downloadFile(multipartFile);

the rest - unchanged

Hope this will help anyone.

Upvotes: 0

Related Questions