简体   繁体   中英

Invalid Address when sending mail using JavaMail

This is my function to prepare recipient list.

public static InternetAddress[] getRecipienEmail(boolean flag) {
        dbconf conf = new dbconf();
        try {
            String sql = null;
            if (flag) {
                sql = "select email_id from EMP_EMAIL_TEST WHERE to_char(dob,'MM-DD')=to_char(sysdate,'MM-DD')";
            } else {
                sql = "select email_id from EMP_EMAIL_TEST WHERE to_char(dob,'MM-DD')<>to_char(sysdate,'MM-DD') or DOB is NULL";
            }

            PreparedStatement preStatement = conf.getConnection().prepareStatement(sql);

            ResultSet result = preStatement.executeQuery();
            ArrayList email = new ArrayList();
            while (result.next()) {
                email.add(result.getString("email_id"));
            }
            InternetAddress[] address = new InternetAddress[email.size()];
            for (int i = 0; i < email.size(); i++) {
                address[i] = new InternetAddress(email.get(i).toString());
            }
            conf.getConnection().close();
            return address;
        } catch (SQLException | AddressException ex) {
           System.out.println(ex.getMessage());
            Logger.getLogger(EmpEmail.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;

    }

When I'm getting Invalid Recipient error.

This is how I'm calling above function. Please suggest, what is wrong here

message.setRecipients(Message.RecipientType.TO,
                    EmpEmail.getRecipienEmail(true));

Please Note: Table has list of emails and It will always return at least one email address.

Update:

I found probable issue. I just found that after below line of code, application through exception.

message.setReplyTo(cc);

I'm using same list of emails in Reply-to. Can't I use multiple email address in Reply-To ?

You can try to see what is inside array email. Might be it has empty string as value. Use debugger or print it to System out like this

for (int i = 0; i < email.size(); i++) {
    System.out.println("email[" + i + "]: " + email.get(i).toString());
    address[i] = new InternetAddress(email.get(i).toString());
}

You can filter out empty and null emails in select query

select email_id from EMP_EMAIL_TEST WHERE to_char(dob,'MM-DD')=to_char(sysdate,'MM-DD') and email_id is not null 
select email_id from EMP_EMAIL_TEST WHERE to_char(dob,'MM-DD')<>to_char(sysdate,'MM-DD') or DOB is NULL and email_id is not null

also you can use Hibernate email validator annotation @Email http://docs.jboss.org/hibernate/validator/5.1/reference/en-US/html/chapter-bean-constraints.html#validator-defineconstraints-hv-constraints

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM