Search code examples
androidsmtpbroadcastreceiverjakarta-mail

Sending mail from javax.mail in android app


I am working on sending mail from a broadcast receiver using javax.mail. The application sends mail when the app is running and in foreground. But when i move the application to background, I get an error

javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
    java.net.ConnectException: failed to connect to smtp.gmail.com/74.125.25.108 (port 587): connect failed: ENETUNREACH (Network is unreachable)

I have made sure that the broadcast receiver is running in background.


Solution

  • Just a little note, I have had trouble doing internet based services from Broadcastreceiver in the past. It would work one time, fail the next. This can be something simple like slow 3G data or a failed post. The trouble with Broadcastreceiver is it gets aggressively shut down by the GC in some cases and is not meant to be long-running. So for things that could fail, or take long, or need to be retried (like sending email), consider rather starting a service from your broadcastreceiver which can continue to retry and keepalive in the event of failure. Not essential, but a good idea (in my experience).