Send mail regularly

Keywords: Java Session SSL REST less

background

Party A's father: During the National Day and the Military Games, the new access business needs to inspect the business daily and send an email to inform the specific situation!

Division I: No problem.

Party A's father: Holidays should be issued, too.

Division I: No problem (grass mud horse).

Initially, it was planned to designate several colleagues to send in turn. As long as the business was not attacked, it was generally no problem. But think about the rest day to deal with work (non-urgent) is not good, in recent years has been doing front-end things, less background contact, after all, also contacted, so decided to develop a regular email program, then online search for information.

Mail Class Selection

Looking at the Internet in general, there are currently two options:

  1. MimeMessage
        String title = createTitle();
        String text = createText();
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.qq.com");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(props, 
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {        
                 return new PasswordAuthentication(from, passwd);
                }
            });
        MimeMessage message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(from));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(title);
            message.setText(text);
            System.out.println(text);
            Transport.send(message);
        } catch(Exception e) {
            e.printStackTrace();
        }
  1. SimpleMail
        mail.setHostName(host);
        mail.setAuthentication(user, passwd);
        mail.setFrom(user);
        mail.setCharset("UTF-8");
        mail.setSubject(title);
        mail.setSSLOnConnect(true);
        mail.setMsg(content);
        mail.addTo(to);
        mail.send();

Refactoring the code locally and testing it. It's sent and received normally. I think SimpleMail looks more concise, so the mail class chose it.

timer

There are a lot of searches on the Internet, not one by one. I use Quartz.
Quartz design has three core classes, namely

  • Scheduler Scheduler Scheduler

The scheduler is equivalent to a container, loaded with tasks and triggers. This class is an interface, representing an independent running container of Quartz. Trigger and JobDetail can be registered in Scheduler. Both have their own groups and names in Scheduler. Groups and names are the basis for Scheduler to locate an object in the container. Trigger's groups and names must be unique. JobDetail Groups and names must also be unique (but can be the same as Trigger's groups and names, because they are different types). Scheduler defines multiple interface methods that allow external access and control of Trigger and JobDetail in containers through groups and names

  • Job task

Define the tasks to be performed. This class is an interface that defines only one method execute(JobExecutionContext context), and writes the Job (task) that needs to be executed regularly in the execute method of the implementation class. The JobExecutionContext class provides some information about the scheduling application. Job runtime information is stored in the JobDataMap instance

  • Trigger trigger

Responsible for setting scheduling strategy. This class is an interface that describes the time-triggering rules that trigger job execution. There are two subclasses: SimpleTrigger and ronTrigger. Simple Trigger is the most suitable choice if and only if scheduling is needed once or periodically with fixed time intervals; CronTrigger can define various scheduling schemes with complex time rules through Cron expression, such as 15:00-16:00 scheduling from Monday to Friday on weekdays, etc.

Development testing

Sender mailbox must open client POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV service. Specifically, it can be set on mailbox settings page, password using authorization code.

  1. Create SendMail class to encapsulate the sending mail logic code
public class SendMail implements Job {

    private static String user = "11111111@qq.com";
    private static String passwd = "passwd";//Authorization code
    private static String to = "22222@qq.com";
    private static String host = "smtp.qq.com";
    
    public static void sendMailForSmtp(String title, String content, String[] tos, String[] ccs) throws EmailException {
        SimpleEmail mail = new SimpleEmail();
        // Setting up Mailbox Server Information
        mail.setHostName(host);
        // Set passwd as authorization code
        mail.setAuthentication(user, passwd);
        // Setting up Mail Sender
        mail.setFrom(user);
        // Setting Mail Code
        mail.setCharset("UTF-8");
        // Setting Mail Theme
        mail.setSubject(title);
        //SSL mode
        mail.setSSLOnConnect(true);
        // Setting Mail Content
//        mail.setMsg(content);
        // Setting up Mail Receiver
//        mail.addTo(to);
        mail.addTo(tos);
        mail.addCc(ccs);
        // Send mail
        MimeMultipart multipart = new MimeMultipart();
        //Mail text  
        BodyPart contentPart = new MimeBodyPart();  
        try {
            contentPart.setContent(content, "text/html;charset=utf-8");
            multipart.addBodyPart(contentPart);  
            //Mail attachment  
            BodyPart attachmentPart = new MimeBodyPart();
            File file = new File("C:\\lutong\\20190918002.log");
            FileDataSource source = new FileDataSource(file);  
            attachmentPart.setDataHandler(new DataHandler(source));  
            attachmentPart.setFileName(MimeUtility.encodeWord(file.getName()));
            multipart.addBodyPart(attachmentPart);
            mail.setContent(multipart);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        System.out.println(JsonUtil.toJson(mail));
        mail.send();
        System.out.println("mail send success!");
    }
    @Override
    public void execute(JobExecutionContext var1) throws JobExecutionException {
        // TODO Auto-generated method stub
        //Multiple Receivers
        String[] tos = {"11111@qq.com","2222@qq.com"};
        //Multiple Copiers
        String[] ccs = {"33333@qq.com","44444@qq.com"};
        try {
            SendMail.sendMailForSmtp("title", "hello <br> ccy", tos, ccs);
        } catch (EmailException e) {
            e.printStackTrace();
        }
    }
}
  1. Create CronTrigger and send tasks on time
public class CronTrigger {
    public static void main(String[] args){
        //Initialize job
        JobDetail job = JobBuilder.newJob(SendMail.class)// Create jobDetail instances and bind Job implementation classes
                .withIdentity("ccy", "group1")//Specify job name, group name
                .build();
        //Definition rules
         Trigger trigger = TriggerBuilder
         .newTrigger()
         .withIdentity("ccy", "group1")//triggel name, group
         .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))//Execute every 5 seconds
         .build();
        Scheduler scheduler = null;
        try {
            scheduler = new StdSchedulerFactory().getScheduler();
            System.out.println("start job...");
            //Register jobs and triggers in task scheduling
            scheduler.scheduleJob(job, trigger);
            //start-up
            scheduler.start();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}

test result

Epilogue

Welcome to Technical Communication Group

If you are interested in the author, you are also welcome to join my friends to discuss technology, exaggeration.
I am writing to gm4118679254

Posted by dannyluked on Fri, 20 Sep 2019 02:32:40 -0700