It is said that we could conveniently sending email in Java. with the requirement of my project, I started to use it for my solution.
package requirement
sending email in Java needs two part of jar, First of it is the JavaEE declared API which do not includes implementation. Another part is provided by vendor, different web server may have disparate support. For me, com.sun.mail has rather enough function. In maven you need to add two <dependency>
Please refer to JavaMail API for further exploration.
coding
I want to implement the mailing function in a clear way, hence I separate it into three parts by sender-infomail-info and mail-sending. First part includes information about the sender, the procedure of sending email regularly needs a logined session from sender, which is similar to the procedure of logining mail.google.com by your gmail account. So you need to fill the account authentication in this class:
I think there is a very strange design in javax.mail, it needs to inherit Authenticator class to provide identity autorization, as below. I still could not figure out the reason, since this could be better designed.
/** * This is a mail service provide mail sending function<BR/> * This class is designed as one to many mailing method<BR/> * you need to provide sender instance as constructor parameter<BR/> * then use <code>send</code> method to send mail * * @author Rugal Bernstein */ @Service publicclassSendMailService {
@Before publicvoidsetUp() { mail = newMail("example@web.com"); mail.setContent("This is a test mail"); mail.setSubject("This is a test subject"); sender = newSender("example@web.com"); sender.setPassword("123456"); instance = newSendMailService(sender);
}
/** * Test of send method, of class MailSender. * * @throws javax.mail.MessagingException */ @Test publicvoidtestSend()throws MessagingException { System.out.println("begin"); instance.send(mail); System.out.println("end"); } }
Seems everything is done! JavaMail API is pulchritude indeed!