Loading...
Spring Framework Reference Documentation 7.0.2의 Email의 한국어 번역본입니다.
아래의 경우에 피드백에서 신고해주신다면 반영하겠습니다.
감사합니다 :)
This section describes how to send email with the Spring Framework.
The following JAR needs to be on the classpath of your 애플리케이션 in order to use the Spring Framework’s email support:
This library is freely available on the web — for example, in Maven Central as
org.eclipse.angus:angus-mail.
The Spring Framework provides a helpful utility library for sending email that shields you from the specifics of the underlying mailing system and is responsible for low-level resource handling on behalf of the client.
The org.springframework.mail package is the root level package for the Spring
Framework’s email support. The central 인터페이스 for sending emails is the MailSender
인터페이스. A simple value 객체 that encapsulates the properties of a simple mail such
as from and to (plus many others) is the SimpleMailMessage 클래스.
This 패키지
also contains a hierarchy of checked 예외 that provide a higher level of
abstraction over the lower level mail system 예외, with the root 예외 being
MailException. See the javadoc
for more information on the rich mail 예외 hierarchy.
The org.springframework.mail.javamail.JavaMailSender 인터페이스 adds specialized
JavaMail features, such as MIME message support to the MailSender 인터페이스
(from which it inherits). JavaMailSender also provides a callback 인터페이스 called
org.springframework.mail.javamail.MimeMessagePreparator for preparing a MimeMessage.
Assume that we have a business 인터페이스 called OrderManager, as the following example shows:
1public interface OrderManager { 2 3 void placeOrder(Order order); 4}
1interface OrderManager { 2 3 fun placeOrder(order: Order) 4}
Further assume that we have a requirement stating that an email message with an order number needs to be generated and sent to a customer who placed the relevant order.
MailSender and SimpleMailMessage UsageThe following example shows how to use MailSender and SimpleMailMessage to send an
email when someone places an order:
1public class SimpleOrderManager implements OrderManager { 2 3 private MailSender mailSender; 4 private SimpleMailMessage templateMessage; 5 6 public void setMailSender(MailSender mailSender) { 7 this.mailSender = mailSender; 8 } 9 10 public void setTemplateMessage(SimpleMailMessage templateMessage) { 11 this.templateMessage = templateMessage; 12 } 13 14 @Override 15 public void placeOrder(Order order) { 16 17 // Do the business calculations... 18 19 // Call the collaborators to persist the order... 20 21 // Create a thread-safe "copy" of the template message and customize it 22 SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage); 23 msg.setTo(order.getCustomer().getEmailAddress()); 24 msg.setText( 25 "Dear " + order.getCustomer().getFirstName() 26 + order.getCustomer().getLastName() 27 + ", thank you for placing order. Your order number is " 28 + order.getOrderNumber()); 29 try { 30 this.mailSender.send(msg); 31 } 32 catch (MailException ex) { 33 // simply log it and go on... 34 System.err.println(ex.getMessage()); 35 } 36 } 37 38}
1class SimpleOrderManager : OrderManager { 2 3 lateinit var mailSender: MailSender 4 lateinit var templateMessage: SimpleMailMessage 5 6 override fun placeOrder(order: Order) { 7 // Do the business calculations... 8 9 // Call the collaborators to persist the order... 10 11 // Create a thread-safe "copy" of the template message and customize it 12 13 val msg = SimpleMailMessage(this.templateMessage) 14 msg.setTo(order.customer.emailAddress) 15 msg.text = ("Dear " + order.customer.firstName 16 + order.customer.lastName 17 + ", thank you for placing order. Your order number is " 18 + order.orderNumber) 19 try { 20 mailSender.send(msg) 21 } catch (ex: MailException) { 22 // simply log it and go on... 23 System.err.println(ex.message) 24 } 25 } 26}
The following example shows the bean 정의 for the preceding 코드:
1@Bean 2JavaMailSender mailSender() { 3 JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); 4 mailSender.setHost("mail.mycompany.example"); 5 return mailSender; 6} 7 8@Bean // this is a template message that we can pre-load with default state 9SimpleMailMessage templateMessage() { 10 SimpleMailMessage message = new SimpleMailMessage(); 11 message.setFrom("[email protected]"); 12 message.setSubject("Your order"); 13 return message; 14} 15 16@Bean 17SimpleOrderManager orderManager(JavaMailSender mailSender, SimpleMailMessage templateMessage) { 18 SimpleOrderManager orderManager = new SimpleOrderManager(); 19 orderManager.setMailSender(mailSender); 20 orderManager.setTemplateMessage(templateMessage); 21 return orderManager; 22}
1@Bean 2fun mailSender(): JavaMailSender { 3 return JavaMailSenderImpl().apply { 4 host = "mail.mycompany.example" 5 } 6} 7 8@Bean // this is a template message that we can pre-load with default state 9fun templateMessage() = SimpleMailMessage().apply { 10 from = "[email protected]" 11 subject = "Your order" 12} 13 14@Bean 15fun orderManager(javaMailSender: JavaMailSender, simpleTemplateMessage: SimpleMailMessage) = 16 SimpleOrderManager().apply { 17 mailSender = javaMailSender 18 templateMessage = simpleTemplateMessage 19 }
1<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> 2 <property name="host" value="mail.mycompany.example"/> 3</bean> 4 5<!-- this is a template message that we can pre-load with default state --> 6<bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage"> 7 <property name="from" value="[email protected]"/> 8 <property name="subject" value="Your order"/> 9</bean> 10 11<bean id="orderManager" class="com.mycompany.businessapp.support.SimpleOrderManager"> 12 <property name="mailSender" ref="mailSender"/> 13 <property name="templateMessage" ref="templateMessage"/> 14</bean>
JavaMailSender and MimeMessagePreparatorThis section describes another 구현 of OrderManager that uses the MimeMessagePreparator
callback 인터페이스. In the following example, the mailSender 프로퍼티 is of type
JavaMailSender so that we are able to use the JavaMail MimeMessage 클래스:
1import jakarta.mail.Message; 2import jakarta.mail.MessagingException; 3import jakarta.mail.internet.InternetAddress; 4import jakarta.mail.internet.MimeMessage; 5 6import jakarta.mail.internet.MimeMessage; 7import org.springframework.mail.MailException; 8import org.springframework.mail.javamail.JavaMailSender; 9import org.springframework.mail.javamail.MimeMessagePreparator; 10 11public class SimpleOrderManager implements OrderManager { 12 13 private JavaMailSender mailSender; 14 15 public void setMailSender(JavaMailSender mailSender) { 16 this.mailSender = mailSender; 17 } 18 19 public void placeOrder(final Order order) { 20 // Do the business calculations... 21 // Call the collaborators to persist the order... 22 23 MimeMessagePreparator preparator = new MimeMessagePreparator() { 24 public void prepare(MimeMessage mimeMessage) throws Exception { 25 mimeMessage.setRecipient(Message.RecipientType.TO, 26 new InternetAddress(order.getCustomer().getEmailAddress())); 27 mimeMessage.setFrom(new InternetAddress("[email protected]")); 28 mimeMessage.setText("Dear " + order.getCustomer().getFirstName() + " " + 29 order.getCustomer().getLastName() + ", thanks for your order. " + 30 "Your order number is " + order.getOrderNumber() + "."); 31 } 32 }; 33 34 try { 35 this.mailSender.send(preparator); 36 } 37 catch (MailException ex) { 38 // simply log it and go on... 39 System.err.println(ex.getMessage()); 40 } 41 } 42 43}
The mail 코드 is a crosscutting concern and could well be a candidate for<br>refactoring into a custom Spring AOP aspect, which could then<br>be run at appropriate joinpoints on the
OrderManagertarget.
The Spring Framework’s mail support ships with the standard JavaMail 구현. See the relevant javadoc for more information.
MimeMessageHelperA 클래스 that comes in pretty handy when dealing with JavaMail messages is
org.springframework.mail.javamail.MimeMessageHelper, which shields you from
having to use the verbose JavaMail API. Using the MimeMessageHelper, it is
pretty easy to create a MimeMessage, as the following example shows:
1// of course you would use DI in any real-world cases 2JavaMailSenderImpl sender = new JavaMailSenderImpl(); 3sender.setHost("mail.host.com"); 4 5MimeMessage message = sender.createMimeMessage(); 6MimeMessageHelper helper = new MimeMessageHelper(message); 7helper.setTo("[email protected]"); 8helper.setText("Thank you for ordering!"); 9 10sender.send(message);
Multipart email messages allow for both attachments and inline 리소스. Examples of inline 리소스 include an image or a 스타일시트 that you want to use in your message but that you do not want displayed as an attachment.
The following example shows you how to use the MimeMessageHelper to send an email
with a single JPEG image attachment:
1JavaMailSenderImpl sender = new JavaMailSenderImpl(); 2sender.setHost("mail.host.com"); 3 4MimeMessage message = sender.createMimeMessage(); 5 6// use the true flag to indicate you need a multipart message 7MimeMessageHelper helper = new MimeMessageHelper(message, true); 8helper.setTo("[email protected]"); 9 10helper.setText("Check out this image!"); 11 12// let's attach the infamous windows Sample file (this time copied to c:/) 13FileSystemResource file = new FileSystemResource(new File("c:/Sample.jpg")); 14helper.addAttachment("CoolImage.jpg", file); 15 16sender.send(message);
The following example shows you how to use the MimeMessageHelper to send an email
with an inline image:
1JavaMailSenderImpl sender = new JavaMailSenderImpl(); 2sender.setHost("mail.host.com"); 3 4MimeMessage message = sender.createMimeMessage(); 5 6// use the true flag to indicate you need a multipart message 7MimeMessageHelper helper = new MimeMessageHelper(message, true); 8helper.setTo("[email protected]"); 9 10// use the true flag to indicate the text included is HTML 11helper.setText("<html><body><img src='cid:identifier1234'></body></html>", true); 12 13// let's include the infamous windows Sample file (this time copied to c:/) 14FileSystemResource res = new FileSystemResource(new File("c:/Sample.jpg")); 15helper.addInline("identifier1234", res); 16 17sender.send(message);
Inline 리소스 are added to the
MimeMessageby using the specifiedContent-ID<br>(identifier1234in the above example). The order in which you add the text<br>and the 리소스 are very important. Be sure to first add the text and then<br>the 리소스. If you are doing it the other way around, it does not work.
The 코드 in the examples shown in the previous sections explicitly created the 콘텐츠 of the email message,
by using methods calls such as message.setText(..). This is fine for simple cases, and it
is okay in the context of the aforementioned examples, where the intent was to show you
the very basics of the API.
In your typical 엔터프라이즈 애플리케이션, though, 개발자 often do not create the 콘텐츠 of email messages by using the previously shown approach for a number of reasons:
Typically, the approach taken to address these issues is to use a 템플릿 라이브러리 (such as FreeMarker) to define the display 구조 of email 콘텐츠. This leaves your 코드 tasked only with creating the 데이터 that is to be rendered in the email 템플릿 and sending the email.
It is definitely a best practice when the 콘텐츠 of your email messages becomes even moderately complex, and, with the Spring Framework’s support 클래스 for FreeMarker, it becomes quite easy to do.
Further Resources
Task Execution and Scheduling