Java method call
I am using this code to send emails to mailboxes.
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 am wondering how I can insert some validation - this email was sent successfully. For example, is there a way to check if there is any exception? If there is no exception to return "Mail sent".
source to share
Take a look here: Java Mail API . Basically you can do 2 things:
- Implement and register
TransportListener
- Catch these exceptions:
SendFailedException - if the send failed due to invalid addresses. MessagingException - if connection is dead or not in connected state
For example:
TransportListener listener = new MyTransportAdapter();
transport.addTransportListener(listener);
Where:
class MyTransportAdapter extends TransportAdapter {
//Implement only methods of interest from TransportAdapter API
}
source to share
Just add a block boolean
and finally
for example:
try{
....
boolean isExceptionThrown = false ;
}
catch (AddressException ae){
ae.printStackTrace();
isExceptionThrown = true ;
}
catch (MessagingException me)
{
me.printStackTrace();
isExceptionThrown = true ;
}
finally{
if (isExceptionThrown == false) return "mail OK sent" ;
}
If you don't have an exception, it means that the SMTP server has decided to deliver your message and will try to deliver it. But the address may not even exist, and the only way to know what to wait and see if you receive "delivery status notifications" is by letting you know, but some server won't even send you those messages.
Basically, if you want a reliable way to send a message, don't use emails.
source to share