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:
- 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();
}
复制代码
- 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 SimpleMail
looks more concise, so the message class we chose it
Timer
A lot of online search, concrete will not describe, I use Quartz
Quartz
design 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
Quartz
the independent operation of the vessel,Trigger
andJobDetail
can be registeredScheduler
, both inScheduler
has its own group and name, and the name of the group isScheduler
to find a basis for positioning the container objects,Trigger
the group and the name must be unique ,JobDetail
group and name must be unique (but can beTrigger
of the same name and the group, because they are different types).Scheduler
It defines a plurality of interface methods, and the name of the group by allowing external access and control vesselTrigger
andJobDetail
- Job tasks defined tasks to be performed. This class is an interface, only defines a method
execute(JobExecutionContext context)
, the implementation class ofexecute
the preparation required to perform a timing processJob
(task),JobExecutionContext
class provides information about the scheduling application.Job
Information stored in the runtimeJobDataMap
instances - Trigger trigger is responsible for setting the scheduling policy. This class is an interface that describes the trigger
job
time trigger rule execution. MainSimpleTrigger
andCronTrigger
two sub-classes. If and only if a required schedule or perform scheduling period at fixed time intervals,SimpleTrigger
is the most suitable choice; andCronTrigger
it canCron
define a regular time scheduling scheme complex expressions: weekdays from Monday to Friday as15:00~16:00
performing 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
- 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();
}
}
}
复制代码
- 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
postscript
Welcome to the technical communication group
If you are interested, we also welcome you add me friends together to discuss technology, I admire the white micro lettergm4118679254