본문 바로가기

Development/Web & Server

[Spring Framework] Email 발송하기~!

1. Pom 파일

<!-- Email -->

<dependency>

    <groupId>javax.mail</groupId>

    <artifactId>mail</artifactId>

    <version>1.4</version>

</dependency>

<dependency>

<groupId>org.apache.velocity</groupId>

<artifactId>velocity</artifactId>

<version>1.7</version>

</dependency>


2. Setting 설정하기


<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">

        <property name="host" value="smtp.gmail.com"/>

        <property name="port" value="25"/>

        <property name="username" value="USER_ID"/>

        <property name="password" value="PASSWORD"/>

        <property name="javaMailProperties">

            <props>

                <prop key="mail.transport.protocol">smtp</prop>

                <prop key="mail.smtp.auth">true</prop>

                <prop key="mail.smtp.starttls.enable">true</prop>

                <prop key="mail.debug">true</prop>

            </props>

        </property>

    </bean>

    

    <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">

      <property name="velocityProperties">

         <value>

            resource.loader=class

            class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader

         </value>

      </property>

   </bean>


3. 소스코드


  @Inject private JavaMailSender mailSender;

@Inject private VelocityEngine velocityEngine;


final MimeMessagePreparator preparator = new MimeMessagePreparator() {

@Override

public void prepare (final MimeMessage mimeMessage) throws Exception {

    final MimeMessageHelper message = new MimeMessageHelper(mimeMessage);

        message.setTo(사용자 이메일);

message.setFrom("aaaa.com");

 message.setSubject("Meme Email Confirm");

final Map<String, Object> model = new HashMap<String, Object>();

model.put("user", user);//User 커스텀 Object

final String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "email/auth_mail.html", "utf-8", model);

message.setText(text, true);

}//end prepare Method

}; 

this.mailSender.send(preparator);


4. html (user라는 객체에 data가 있으면 데이터로 치환)


<html>

<body>


<h3>

Welcome Meme <a href="http://localhost/${user.data}">Authroize</a>

</h3>


</body>

</html>