Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call java method confirmation

Tags:

java

I'm using this code to send e-mails to mail boxes.

private String sendFromGMail(String from, String pass, String[] to, String subject, String body)
    {
        Properties props = System.getProperties();
        String host = "smtp.gmail.com";
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props);
        MimeMessage message = new MimeMessage(session);

        try
        {
            message.setFrom(new InternetAddress(from));
            InternetAddress[] toAddress = new InternetAddress[to.length];

            // To get the array of addresses
            for (int i = 0; i < to.length; i++)
            {
                toAddress[i] = new InternetAddress(to[i]);
            }

            for (int i = 0; i < toAddress.length; i++)
            {
                message.addRecipient(Message.RecipientType.TO, toAddress[i]);
            }

            message.setSubject(subject);
            message.setText(body);
            Transport transport = session.getTransport("smtp");
            transport.connect(host, from, pass);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        }
        catch (AddressException ae)
        {
            ae.printStackTrace();
        }
        catch (MessagingException me)
        {
            me.printStackTrace();
        }

     return "message is send";
    }

I'm interested how I can inset some check is this e-mail successfully send. For example is there any way to check is there any Exception? If there no Exception to return "Mail is send".

like image 758
Peter Penzov Avatar asked Apr 20 '26 05:04

Peter Penzov


1 Answers

Look here: Java Mail API. Basically you can do 2 things:

  1. Implement and Register a TransportListener
  2. Catch these exceptions:

SendFailedException - if the send failed because of invalid addresses. MessagingException - if the connection is dead or not in the connected state

For example:

TransportListener listener = new MyTransportAdapter();
transport.addTransportListener(listener);

where:

class MyTransportAdapter extends TransportAdapter {
//Implement only methods of interest from TransportAdapter API
}
like image 160
ACV Avatar answered Apr 22 '26 19:04

ACV