简体   繁体   中英

Send Email in Specific time

I use below code to send an Email. Just create an object and call the method of that object.

package com.kap.globalreport;
public class Mainmethod930 { 
    public static void main(String[] args) {
        EmailReport930 emailReport930 = new EmailReport930();
        emailReport930.sendEmail("emailContent","Subject");
    }
}

above I create object and call below sendEmail method.

package com.kap.globalreport;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Date;
import java.util.Properties;

public class EmailReport930 implements Runnable {

final private String SMTP_SERVER = "166.62.121.14";
final private String SMTP_PORT = "587";
final private String ROWEL_EMAIL = "dumidu@kapruka.com";
final private String FROM_EMAIL = "cargillspaymenterros@kapruka.com";
final private String FROM_EMAIL_PASSWORD = "cpay@55";
private String emailContent;
private String subject;

public String getEmailContent() {
    return emailContent;
}

public void setEmailContent(String emailContent) {
    this.emailContent = emailContent;
}

public String getSubject() {
    return subject;
}

public void setSubject(String subject) {
    this.subject = subject;
}

private void setEmail(String emailContent, String subject) {
    if (emailContent != null && subject != null) {
        sendEmail(emailContent, subject);
    }
}

public void sendEmail(String emailContent, String subject) {
    try {

        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", SMTP_SERVER);
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.auth", "true");
        Session mailSession = Session.getInstance(props, new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(FROM_EMAIL, FROM_EMAIL_PASSWORD);
            }
        });
        mailSession.setDebug(true);
        MimeMessage message = new MimeMessage(mailSession);
        message.setFrom(new InternetAddress(FROM_EMAIL));
        message.addHeader("site", "kapruka.com");
        message.addHeader("service", "Cargills Payment Service");
        message.setSentDate(new Date());
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(ROWEL_EMAIL));
        message.setSubject(subject);

        MimeMultipart mimeMultipart = new MimeMultipart();
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(emailContent, "text/html; charset=utf-8");
        messageBodyPart.setContent("<h1>SMTP_PORT</h1>", "text/html");
        mimeMultipart.addBodyPart(messageBodyPart);
        message.setContent(mimeMultipart);

        Transport.send(message);
        System.out.println("Email Sent successfully....");

    } catch (MessagingException mex) {
        mex.printStackTrace();
    }
}

@Override
public void run() {
    setEmail(emailContent, subject);
}
}

I want to run this send email method in specific time.I also want to get data from data base using hibernate framework. Email should be send with above data.

Normally there are four different ways to running a task periodically:

  1. Timer
  2. ScheduledExecutorService
  3. Spring Scheduler
  4. Quartz

In your case since you are not using any framework, you could do it using native java with timer and ScheduledExecutorService as:

public class PeriodicTask {
    public static void main(String... args) {
        // System.out.println(LocalTime.ofSecondOfDay(getDelayTo(15, 4)));
        // System.out.println(LocalTime.ofSecondOfDay(getDelayTo(16, 4)));
        testTimer();
        testScheduledExecutorService();
    }

    private static long getDelayTo(int hour, int minute) {
        LocalDateTime currentTime = LocalDateTime.now();
        long gapToSpecified = ChronoUnit.SECONDS.between(currentTime, LocalDate.now().atTime(hour, minute));
        if (gapToSpecified < 0) { // the time already passed => do it tomorrow;
            return ChronoUnit.SECONDS.between(currentTime, LocalDate.now().plusDays(1).atTime(hour, minute));
        }
        return gapToSpecified; // not passed, do it later today at the specified time;
    }

    public static void testTimer() {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println(LocalDateTime.now());
                System.out.println("Hello world");
            }
        }, getDelayTo(13, 0), TimeUnit.DAYS.toSeconds(1));
    }

    public static void testScheduledExecutorService() {
        Executors.newScheduledThreadPool(1).scheduleWithFixedDelay(() -> {
                    System.out.println("Hello World!");
                }, getDelayTo(13, 0), TimeUnit.DAYS.toSeconds(1), TimeUnit.SECONDS);
    }
}

Use a java.util.Timer and schedule your work.

Timer.schedule(TimerTask task, Date firstTime, long period)

~ Timer (Java Platform SE 7 ) ~

Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 13);
c.set(Calendar.MINUTE, 00);
c.set(Calendar.SECOND, 00);

Timer timer = new Timer();
timer.schedule(new TimerTask() {
    @Override
    public void run() {
        //Call your method here
        //setEmail(emailContent, subject);
    }
}, c.getTime(), 86400000);

//24hrs == 86400000ms

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM