Send automatic mail on specific date through java

2019-01-28 08:16发布

问题:

I am using Java mail API to send email through my java application. But I want to send it automatically on future date i.e. any specific date of every month/year. I have used my ISP's SMTP server to send email on mentioned id.I have referred the below available example on net. How to set any specific date here.I have tried SimpleDateFormat and set it here but it still sends mail immediately but set its sent date as mentioned specific date. Is there any other way to send automatic email on mentioned date and time?

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

// Send a simple, single part, text/plain e-mail
public class TestEmail {

public static void main(String[] args) {

    // SUBSTITUTE YOUR EMAIL ADDRESSES HERE!!!
    String to = "abc@abc.com";
    String from = "abc@abc.com";
    // SUBSTITUTE YOUR ISP'S MAIL SERVER HERE!!!
    String host = "smtp.yourisp.net";

    // Create properties, get Session
    Properties props = new Properties();

    // If using static Transport.send(),
    // need to specify which host to send it to
    props.put("mail.smtp.host", host);
    // To see what is going on behind the scene
    props.put("mail.debug", "true");
    Session session = Session.getInstance(props);

    try {
        // Instantiatee a message
        Message msg = new MimeMessage(session);

        //Set message attributes
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = {new InternetAddress(to)};
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject("Test E-Mail through Java");
        msg.setSentDate(new Date());

        // Set message content
        msg.setText("This is a test of sending a " +
                    "plain text e-mail through Java.\n" +
                    "Here is line 2.");

        //Send the message
        Transport.send(msg);
    }
    catch (MessagingException mex) {
        // Prints all nested (chained) exceptions as well
        mex.printStackTrace();
    }
}
}//End of class

回答1:

Configure Quartz Job for it. Use cron trigger to specify the execution event



回答2:

If you're using an EJB 3.0+ container, you could easily use the timer service.

You need to make a session bean, and either implement the TimedObject interface or annotate a method with @Timeout. You can get an instance of the TimerService from the InitialContext via getTimerService(), then create a timer with one of the createTimer() variants. It can take an interval, or a Date object specifying when it expires...