How to get Bounced mails in java

236 views Asked by At

I am implementing a Bulk mail application, in this applica This link.

I am able to connect to the server and and send the emails to the destination addresses, but I want to identify the undelivered mails.

By using below program I am able to get the email subjects. But based on the subject it will be difficult to identify the exact undelivered mails.

public static void main(String[] args) {

        Properties props = System.getProperties();
        props.setProperty("mail.host", host);
        props.setProperty("mail.user", user);
        props.setProperty("mail.from", from);
        //props.setProperty("mail.debug", "true");
        //props.setProperty("mail.domain", domain);
        try {
        Session session = Session.getInstance(props, null);
        Store store = session.getStore(protocol);
        Session session1 = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(user, password);
                    }
                });

        
        System.out.println((store.isConnected())?"Already Connected":"Not Already Connected");

        store.connect(host, port, user, password);
         
        
        Folder inbox = store.getFolder("INBOX");
        System.out.println("folder>>>" + inbox.getFullName() + "<<<");
        System.out.println("folder URLName>>>" + inbox.getURLName() + "<<<");
        System.out.println((inbox.exists()?"folder exists":"folder does not exist"));

        int folderType = inbox.getType();
        System.out.println("folder type>>>" + folderType + "<<<");

        inbox.open(Folder.READ_WRITE);
        System.out.println("Message Count:" + inbox.getMessageCount());

        Message[] m = inbox.getMessages();

        for (int x = 0; x < m.length; x++) {
            System.out.println(m[x].getSubject());
        }
        inbox.close(false);
        store.close();
        }catch(Exception e) {
            System.out.println(e.getLocalizedMessage());
        }
    }

How can I get the undelivered mails(Bounced).

I am using Hmailserver as my mail server.

1

There are 1 answers

4
Farukh Tariq On

You can use this below code

MimeMessage payload = (MimeMessage) message.getPayload();
Multipart mp = (Multipart) payload.getContent();
for (int i = 0; i < mp.getCount(); i++) {
                    BodyPart bodyPart = mp.getBodyPart(i);
                    StringWriter writer = new StringWriter();
                    IOUtils.copy(bodyPart.getInputStream(), writer);
                    System.out.println("Content inputstream: " +  writer.toString());


}