How to check attachment in different formats java mail

To check the attachment in different formats using Java Mail, you can use the following approaches:

  1. Using MimeMessage and MimePart classes:
    
    import javax.mail.*;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimePart;

// Get the MimeMessage object MimeMessage msg = (MimeMessage) session.getMessage();

// Get the MimePart object MimePart part = (MimePart) msg.getContent();

// Check the attachment format if (part.isMimeType("text/plain")) { System.out.println("Attachment is a plain text file"); } else if (part.isMimeType("application/pdf")) { System.out.println("Attachment is a PDF file"); } else if (part.isMimeType("image/jpeg")) { System.out.println("Attachment is a JPEG image"); } else { System.out.println("Attachment is of unknown format"); }

2. **Using `MimeMessage` and `MimeBodyPart` classes**:
```java
import javax.mail.*;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeBodyPart;

// Get the MimeMessage object
MimeMessage msg = (MimeMessage) session.getMessage();

// Get the MimeBodyPart object
MimeBodyPart part = (MimeBodyPart) msg.getContent();

// Check the attachment format
if (part.getContentType().startsWith("text/plain")) {
    System.out.println("Attachment is a plain text file");
} else if (part.getContentType().startsWith("application/pdf")) {
    System.out.println("Attachment is a PDF file");
} else if (part.getContentType().startsWith("image/jpeg")) {
    System.out.println("Attachment is a JPEG image");
} else {
    System.out.println("Attachment is of unknown format");
}
  1. Using MimeMessage and DataSource classes:
    
    import javax.mail.*;
    import javax.mail.internet.MimeMessage;
    import javax.activation.DataSource;

// Get the MimeMessage object MimeMessage msg = (MimeMessage) session.getMessage();

// Get the DataSource object DataSource ds = (DataSource) msg.getContent();

// Check the attachment format if (ds.getContentType().startsWith("text/plain")) { System.out.println("Attachment is a plain text file"); } else if (ds.getContentType().startsWith("application/pdf")) { System.out.println("Attachment is a PDF file"); } else if (ds.getContentType().startsWith("image/jpeg")) { System.out.println("Attachment is a JPEG image"); } else { System.out.println("Attachment is of unknown format"); }


In each of these approaches, you need to:

1. Get the `MimeMessage` object from the Java Mail session.
2. Get the `MimePart`, `MimeBodyPart`, or `DataSource` object from the `MimeMessage` object.
3. Check the `contentType` property of the attachment to determine its format.

Note that the `contentType` property may contain additional information, such as the file name and encoding, so you may need to parse this property to extract the relevant information.