Статьи

Учебник по интеграции Spring, Quartz и JavaMail

Кварц — это структура планирования заданий, которая используется для планирования заданий, выполняемых в указанное время. JavaMail — это API для отправки / получения сообщений электронной почты из приложений Java.

Spring имеет точки интеграции для интеграции Quartz и JavaMail, что упрощает использование этих API. Давайте создадим небольшое демонстрационное приложение, чтобы показать, как интегрировать Spring + Quartz + JavaMail.

Наше приложение — отправлять электронные письма с пожеланиями дня рождения друзьям каждый день в 6 утра.

Email.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package com.sivalabs.reminders;
  
import java.util.ArrayList;
import java.util.List;
  
public class Email
{
 private String from;
 private String[] to;
 private String[] cc;
 private String[] bcc;
 private String subject;
 private String text;
 private String mimeType;
 private List<Attachment> attachments = new ArrayList<Attachment>();
   
 public String getFrom()
 {
  return from;
 }
 public void setFrom(String from)
 {
  this.from = from;
 }
 public String[] getTo()
 {
  return to;
 }
 public void setTo(String... to)
 {
  this.to = to;
 }
 public String[] getCc()
 {
  return cc;
 }
 public void setCc(String... cc)
 {
  this.cc = cc;
 }
 public String[] getBcc()
 {
  return bcc;
 }
 public void setBcc(String... bcc)
 {
  this.bcc = bcc;
 }
 public String getSubject()
 {
  return subject;
 }
 public void setSubject(String subject)
 {
  this.subject = subject;
 }
 public String getText()
 {
  return text;
 }
 public void setText(String text)
 {
  this.text = text;
 }
 public String getMimeType()
 {
  return mimeType;
 }
 public void setMimeType(String mimeType)
 {
  this.mimeType = mimeType;
 }
 public List<Attachment> getAttachments()
 {
  return attachments;
 }
 public void addAttachments(List<Attachment> attachments)
 {
  this.attachments.addAll(attachments);
 }
 public void addAttachment(Attachment attachment)
 {
  this.attachments.add(attachment);
 }
 public void removeAttachment(int index)
 {
  this.attachments.remove(index);
 }
 public void removeAllAttachments()
 {
  this.attachments.clear();
 }
}

Attachment.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.sivalabs.reminders;
  
public class Attachment
{
 private byte[] data;
 private String filename;
 private String mimeType;
 private boolean inline;
   
 public Attachment()
 {
 }
   
 public Attachment(byte[] data, String filename, String mimeType)
 {
  this.data = data;
  this.filename = filename;
  this.mimeType = mimeType;
 }
 public Attachment(byte[] data, String filename, String mimeType, boolean inline)
 {
  this.data = data;
  this.filename = filename;
  this.mimeType = mimeType;
  this.inline = inline;
 }
 public byte[] getData()
 {
  return data;
 }
 public void setData(byte[] data)
 {
  this.data = data;
 }
 public String getFilename()
 {
  return filename;
 }
 public void setFilename(String filename)
 {
  this.filename = filename;
 }
  
 public String getMimeType()
 {
  return mimeType;
 }
  
 public void setMimeType(String mimeType)
 {
  this.mimeType = mimeType;
 }
  
 public boolean isInline()
 {
  return inline;
 }
  
 public void setInline(boolean inline)
 {
  this.inline = inline;
 }
   
}

EmailService.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.sivalabs.reminders;
  
import java.util.List;
  
import javax.activation.DataSource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;
  
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
  
public class EmailService
{
 private JavaMailSenderImpl mailSender = null;
 public void setMailSender(JavaMailSenderImpl mailSender)
 {
  this.mailSender = mailSender;
 }
   
 public void sendEmail(Email email) throws MessagingException {
  MimeMessage mimeMessage = mailSender.createMimeMessage();
  // use the true flag to indicate you need a multipart message
  boolean hasAttachments = (email.getAttachments()!=null &&
         email.getAttachments().size() > 0 );
  MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, hasAttachments);
  helper.setTo(email.getTo());
  helper.setFrom(email.getFrom());
  helper.setSubject(email.getSubject());
  helper.setText(email.getText(), true);
    
  List<Attachment> attachments = email.getAttachments();
     if(attachments != null && attachments.size() > 0)
     {
      for (Attachment attachment : attachments)
      {
          String filename = attachment.getFilename() ;
          DataSource dataSource = new ByteArrayDataSource(attachment.getData(),
                 attachment.getMimeType());
          if(attachment.isInline())
          {
           helper.addInline(filename, dataSource);
          }else{
           helper.addAttachment(filename, dataSource);
          }
      }
     }
    
  mailSender.send(mimeMessage);
 }
}

BirthdayWisherJob.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.sivalabs.reminders;
  
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
  
import javax.mail.MessagingException;
  
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.QuartzJobBean;
  
public class BirthdayWisherJob extends QuartzJobBean
{
   
 private EmailService emailService;
 public void setEmailService(EmailService emailService)
 {
  this.emailService = emailService;
 }
   
 @Override
 protected void executeInternal(JobExecutionContext context) throws JobExecutionException
 {
  System.out.println("Sending Birthday Wishes... ");
  List<User> usersBornToday = getUsersBornToday();
  for (User user : usersBornToday)
  {
   try
   {
    Email email = new Email();
    email.setFrom("admin@sivalabs.com");
    email.setSubject("Happy BirthDay");
    email.setTo(user.getEmail());
    email.setText("<h1>Dear "+user.getName()+
      ",Many Many Happy Returns of the day :-)</h1>");
       
    byte[] data = null;
    ClassPathResource img = new ClassPathResource("HBD.gif");
    InputStream inputStream = img.getInputStream();
    data = new byte[inputStream.available()];
    while((inputStream.read(data)!=-1));
     
    Attachment attachment = new Attachment(data, "HappyBirthDay",
      "image/gif", true);
    email.addAttachment(attachment);
     
    emailService.sendEmail(email);
   }
   catch (MessagingException e)
   {
    e.printStackTrace();
   }
   catch (Exception e)
   {
    e.printStackTrace();
   }
  }
 }
   
 private List<User> getUsersBornToday()
 {
  List<User> users = new ArrayList<User>();
  User user1 = new User("Siva Prasad", "sivaprasadreddy.k@gmail.com", new Date());
  users.add(user1);
  User user2 = new User("John", "abcd@gmail.com", new Date());
  users.add(user2);
  return users;
 }
}

applicationContext.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<beans>
  
 <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
 <property name="triggers">
  <list>
   <ref bean="birthdayWisherCronTrigger" />
  </list>
 </property>
 </bean>
 <bean id="birthdayWisherCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
  <property name="jobDetail" ref="birthdayWisherJob" />
  <!-- run every morning at 6 AM -->
  <property name="cronExpression" value="0/5 * * * * ?" />
 </bean>
  
 <bean name="birthdayWisherJob" class="org.springframework.scheduling.quartz.JobDetailBean">
  <property name="jobClass" value="com.sivalabs.reminders.BirthdayWisherJob" />
  <property name="jobDataAsMap">
   <map>
    <entry key="emailService" value-ref="emailService"></entry>
   </map>
  </property>
 </bean>
   
 <bean id="emailService" class="com.sivalabs.reminders.EmailService">
  <property name="mailSender" ref="mailSender"></property>
 </bean>
   
 <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
  <property name="defaultEncoding" value="UTF-8"/>
  <property name="host" value="smtp.gmail.com" />
  <property name="port" value="465" />
  <property name="protocol" value="smtps" />
  <property name="username" value="admin@gmail.com"/>
  <property name="password" value="*****"/>
  <property name="javaMailProperties">
   <props>
    <prop key="mail.smtps.auth">true</prop>
    <prop key="mail.smtps.starttls.enable">true</prop>
    <prop key="mail.smtps.debug">true</prop>
   </props>
  </property>
 </bean>
   
</beans>

TestClient.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
package com.sivalabs.reminders;
  
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
  
public class TestClient {
   
 public static void main(String[] args)
 {
  ApplicationContext ctx =
     new ClassPathXmlApplicationContext("applicationContext.xml");
 }
  
}

Ссылка: руководство по интеграции Spring + Quartz + JavaMail от нашего партнера по JCG Сивы в блоге « Мои эксперименты по технологии» .

Статьи по Теме :