오윤아
오윤아

Reputation: 11

The image is base64 encoded but cannot be emailed

This method encodes the image file into base64 and then transmits it.

You will receive a notification that the email attachment has been successfully completed and the transfer was successful. The base64 encoded value was wrapped with 76 characters each. However, there are times when emails are delivered normally, and there are times when they are delivered abnormally. There are no errors. Is the image size wrong?

String base64EncodedImage = base64EncodeImage(sendMailRequestDTO.getFile());
int lineLength = 76;
buf.delete(0, buf.length())
        .append("--boundary_text\r\n")
        .append("Content-Type: application/octet-stream; name=\"image.png\"\r\n")
        //.append("Content-Type: image/png\r\n")
        .append("Content-Disposition: attachment; filename=\"image.png\"\r\n")
        .append("Content-Transfer-Encoding: base64\r\n")
        .append("--boundary_text\r\n");
        for (int i = 0; i < base64EncodedImage.length(); i += lineLength) {
            int end = Math.min(i + lineLength, base64EncodedImage.length());
            buf.append(base64EncodedImage.substring(i, end))
                .append("\r\n");
        }
        buf.append("\r\n")
        .append("--boundary_text\r\n")
        .append("--boundary_text--\r\n");
sendCommand(writer, buf.toString());

private static void sendCommand(BufferedWriter writer, String command) throws IOException {
    buffer.delete(0, buffer.length());
    buffer.append(command);
    buffer.append("\r\n");
    log.debug("command ::>> {}", command);
    writer.write(buffer.toString());
    writer.flush();
}

private static String base64EncodeImage(MultipartFile file) {
    try {
        byte[] imageBytes = file.getBytes();
        return Base64.getEncoder().encodeToString(imageBytes);
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}

I tried changing the content type, png to jpg, but it failed.

Upvotes: 1

Views: 51

Answers (0)

Related Questions