Sending a message

Sending a message

background

Party Dad: new access service during the National Day military transport and patrol service will need to send a message every day and inform the specific circumstances!
Division I: no problem.
Party Dad: Oh vacation should be made.
Division I: no problem (mud horse).

Just specify several colleagues began planning to send in turn, it will not be attacked as long as the business is generally not a problem. But consider a rest day but also on your work (non-urgent) of sorts in recent years have been doing things the front end, back-end touch less, after all, have come across, so I decided to engage in a regular program to send mail , then the Internet to find information.

Select the message class

Under generally looked online, there are 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();
复制代码

Reconstructed in native code and tested, both sending and receiving normal, personally feel SimpleMaillooks more concise, so the message class we chose it

Timer

A lot of online search, concrete will not describe, I use Quartz Quartzdesign has three core categories, namely

  • Scheduler dispatcher scheduler corresponding to one container, and trigger the task of loading. This class is an interface, a representative of Quartzthe independent operation of the vessel, Triggerand JobDetailcan be registered Scheduler, both in Schedulerhas its own group and name, and the name of the group is Schedulerto find a basis for positioning the container objects, Triggerthe group and the name must be unique , JobDetailgroup and name must be unique (but can be Triggerof the same name and the group, because they are different types). SchedulerIt defines a plurality of interface methods, and the name of the group by allowing external access and control vessel TriggerandJobDetail
  • Job tasks defined tasks to be performed. This class is an interface, only defines a method execute(JobExecutionContext context), the implementation class of executethe preparation required to perform a timing process Job(task), JobExecutionContextclass provides information about the scheduling application. JobInformation stored in the runtime JobDataMapinstances
  • Trigger trigger is responsible for setting the scheduling policy. This class is an interface that describes the trigger jobtime trigger rule execution. Main SimpleTriggerand CronTriggertwo sub-classes. If and only if a required schedule or perform scheduling period at fixed time intervals, SimpleTriggeris the most suitable choice; and CronTriggerit can Crondefine a regular time scheduling scheme complex expressions: weekdays from Monday to Friday as 15:00~16:00performing scheduling

Development and testing

The sender mailbox must open the client POP3 / IMAP / SMTP / Exchange / CardDAV / CalDAV services, specific settings can be set in the mailbox page, password authorization code

  1. Create SendMail class, to send the message code logic package
public class SendMail implements Job {

	private static String user = "[email protected]";
	private static String passwd = "passwd";//授权码
	private static String to = "[email protected]";
	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();
		// 设置邮箱服务器信息
		mail.setHostName(host);
		// 设置密码验证器passwd为授权码
		mail.setAuthentication(user, passwd);
		// 设置邮件发送者
		mail.setFrom(user);
		// 设置邮件编码
		mail.setCharset("UTF-8");
		// 设置邮件主题
		mail.setSubject(title);
		//SSL方式
		mail.setSSLOnConnect(true);
		// 设置邮件内容
//		mail.setMsg(content);
		// 设置邮件接收者
//		mail.addTo(to);
		mail.addTo(tos);
		mail.addCc(ccs);
		// 发送邮件
		MimeMultipart multipart = new MimeMultipart();
		//邮件正文  
        BodyPart contentPart = new MimeBodyPart();  
        try {
			contentPart.setContent(content, "text/html;charset=utf-8");
	        multipart.addBodyPart(contentPart);  
	        //邮件附件  
	        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
		//多个接收者
		String[] tos = {"[email protected]","[email protected]"};
		//多个抄送者
		String[] ccs = {"[email protected]","[email protected]"};
		try {
			SendMail.sendMailForSmtp("title", "hello <br> ccy", tos, ccs);
		} catch (EmailException e) {
			e.printStackTrace();
		}
	}
}
复制代码
  1. Creating CronTrigger, regularly send mission
public class CronTrigger {
	public static void main(String[] args){
		//初始化job
		JobDetail job = JobBuilder.newJob(SendMail.class)// 创建 jobDetail 实例,绑定 Job 实现类
				.withIdentity("ccy", "group1")//指明job名称、所在组名称
				.build();
		//定义规则
		 Trigger trigger = TriggerBuilder
		 .newTrigger()
		 .withIdentity("ccy", "group1")//triggel名称、组
		 .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))//每隔5s执行
		 .build();
		Scheduler scheduler = null;
		try {
			scheduler = new StdSchedulerFactory().getScheduler();
			System.out.println("start job...");
			//把作业和触发器注册到任务调度中
			scheduler.scheduleJob(job, trigger);
			//启动
			scheduler.start();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}
}
复制代码

Test Results

mail.png

postscript

Welcome to the technical communication group

weixinqun_1.png
If you are interested, we also welcome you add me friends together to discuss technology, I admire the white micro letter gm4118679254

Guess you like

Origin juejin.im/post/5d8490a8f265da03f47c5aef