Hanynowsky
Hanynowsky

Reputation: 3010

Java mail how to send automatically an email on condition

Never used Java mail before.

In my JSF web app, I have an entity (followUp) with a property private Date checkDate; that corresponds to an Animal entity. (An Animal has many followup records). Otherwise:

The user must each 3 months create a new record in {followUp} and mark it as checked and supply the date of his action which is "checkDate". But since the user is so lazy, he does that for only few Animals. So he actually wants to be alerted by email for Animals that have not been checked for more than 3 months. Example: I create a followUp record for Animal 'A' on 01/01/2011, then on approximatively 01/04/2011, the user receives an Email alerting him to go check Animal B followup.

The web application is running on Local enterprise Network.

All I Know is that snippet :

import javax.mail.*;
import javax.mail.internet.*;

import java.util.Properties;

class SimpleMail {
    public static void main(String[] args) throws Exception{
      Properties props = new Properties();
      props.setProperty("mail.transport.protocol", "smtp");
      props.setProperty("mail.host", "mymail.server.org");
      props.setProperty("mail.user", "emailuser");
      props.setProperty("mail.password", "");

      Session mailSession = Session.getDefaultInstance(props, null);
      Transport transport = mailSession.getTransport();

      MimeMessage message = new MimeMessage(mailSession);
      message.setSubject("Testing javamail plain");
      message.setContent("This is a test", "text/plain");
      message.addRecipient(Message.RecipientType.TO,
           new InternetAddress("[email protected]"));

      transport.connect();
      transport.sendMessage(message,
          message.getRecipients(Message.RecipientType.TO));
      transport.close();
    }
}

Should I create, a Servlet Filter, A Listener, An Application Scoped backing beans, for that purpose? A query that loops on followUp records and returns the last record's checkDate and compares it to Today date?

Any help will do. Regards.

Upvotes: 4

Views: 4522

Answers (1)

BalusC
BalusC

Reputation: 1109072

Based on your question history I know that you're using Glassfish 3 (Java EE 6 with EJB 3.1), so I'd suggest to create a @Singleton EJB with @Schedule method which executes in the background at specified intervals, for example daily at midnight (00:00:00).

@Singleton
public class MailReminder {

    @Schedule(hour="0", minute="0", second="0", persistent=false)
    public void run() {
        // Do your check and mail job here.
    }

}

That's it. No further configuration is necessary. For testing purposes you could use

    @Schedule(hour="*", minute="*/1", second="0", persistent=false)

to let it run every minute.

See also:

Upvotes: 5

Related Questions