This is the first time I've written something in Java so I'm leaning slowly but I am hard stuck on how to fix this issue. I'm having an issue getting the images that a user inserts into my JEditorPane editerPane to send as an embedded image instead of a file attachment in the email.
private static void embedAndSendEmail(JEditorPane editorPane) throws IOException, BadLocationException, URISyntaxException {
HTMLDocument doc = (HTMLDocument) editorPane.getDocument();
ElementIterator iterator = new ElementIterator(doc);
Element element;
// Collect images to embed
List<File> imageFiles = new ArrayList<>();
while ((element = iterator.next()) != null) {
AttributeSet attrs = element.getAttributes();
Object nameAttr = attrs.getAttribute(StyleConstants.NameAttribute);
if (nameAttr instanceof HTML.Tag) {
HTML.Tag tag = (HTML.Tag) nameAttr;
if (tag == HTML.Tag.IMG) {
String src = (String) attrs.getAttribute(HTML.Attribute.SRC);
if (src != null && src.startsWith("file:///")) {
// Read image data from editor pane
InputStream inputStream = new URL(src).openStream();
byte[] imageData = inputStream.readAllBytes();
String base64Image = Base64.getEncoder().encodeToString(imageData);
// Replace src attribute with base64 data
String newSrc = "data:image/png;base64," + base64Image;
doc.setInnerHTML(element, "<img src=\"" + newSrc + "\">");
// Add image file to the list (for sending email later)
String filePath = new URI(src).getPath(); // Convert URL to file path
imageFiles.add(new File(filePath));
}
}
}
}
}
I've tried to go the Base64 route even though I know it's not as reliable as using Mimebodypart() but I am trying to send out the users inserted image.
Below I am putting the code that interacts with each other to get the email sent out minus the panels and buttons. The code below is trying to embed those images but has the same result of it sending as an attachment.
public class testing {
private static void createAndShowGUI() {
JFrame frame = new JFrame("Mailgun");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1280, 720);
//Listener to insert an image upon clicking
imageInsert.addActionListener(e -> {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Images", "jpg", "jpeg", "png", "gif"));
if (fileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
File imageFile = fileChooser.getSelectedFile();
insertImage(editorPane, imageFile);
}
});
JButton sendButton = new JButton("Send Email");
sendButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String to = emailField.getText();
String subject = subjectField.getText();
String content = "<html><body>"
+ editorPane.getText()
+"</body></html>";
//Made to not allow an email to be sent till fields are not empty
if (to.isEmpty() || subject.isEmpty() || content.isEmpty()) {
JOptionPane.showMessageDialog(frame, "Please fill in all fields.");
return;
}
try {
sendEmail(to, subject, content, imageFiles);
} catch (IOException | MessagingException e1) {
e1.printStackTrace();
}
}
}
private static void sendEmail(String to, String subject, String content, List<File> imageFiles) throws IOException, MessagingException {
final String username = "";
final String password = "";
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.mailgun.com");
properties.put("mail.smtp.port", "587");
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
MimeMultipart multipart = new MimeMultipart("related");
try {
for (File imageFile : imageFiles) {
MimeBodyPart imagePart = new MimeBodyPart();
DataSource ds = new FileDataSource(imageFile);
imagePart.setDataHandler(new DataHandler(ds));
imagePart.setHeader("Content-ID", "<image>");
imagePart.setDisposition(MimeBodyPart.INLINE);
imagePart.setFileName(imageFile.getName());
multipart.addBodyPart(imagePart);
}
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
// Set the content of the message to the multipart
message.setContent(multipart);
// Send message
Transport.send(message);
JOptionPane.showMessageDialog(null, "Email sent successfully.");
} catch (MessagingException e) {
JOptionPane.showMessageDialog(null, "Failed to send email: " + e.getMessage());
e.printStackTrace();
}
}
}
Truly don't know where to go from here, any advice is greatly appreciated!