지메일 보내기 SMTP
2021. 8. 4. 12:09ㆍ(구)공부/Spring
728x90
1) 보안 수준이 낮은 앱의 액세스 사용
https://www.google.com/settings/security/lesssecureapps
2) 내 Google 계정에 대한 액세스 허용
https://accounts.google.com/DisplayUnlockCaptcha
pom.xml - 추가
<!-- mail -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.6</version>
</dependency>
root-context - 추가
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="port" value="587" />
<property name="username" value="지메일 아이디" />
<property name="password" value="지메일 비번" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
</props>
</property>
</bean>
컨트롤러에 메소드 추가
package com.cos.controller;
import javax.inject.Inject;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.cos.service.CategoryService;
@Controller
public class AdminController {
@Inject
private CategoryService ctService;
@Inject // root-context.xml에서 생성된 객체를 주입
private JavaMailSender mailSender;
@RequestMapping(value = "/mailSend", method = RequestMethod.POST)
public String mailSend(@RequestParam("userName") final String name,
@RequestParam("userEmail") final String fromEmail,
@RequestParam("message") final String msg,
@RequestParam("adminEmail") final String toEmail,
Model model) throws Exception{
final MimeMessagePreparator preparator = new MimeMessagePreparator() {
@Override public void prepare(MimeMessage mimeMessage) throws Exception {
final MimeMessageHelper helper =
new MimeMessageHelper(mimeMessage, true, "UTF-8");
// helper.setTo(toEmail);
helper.setTo(toEmail);
helper.setFrom(new InternetAddress(fromEmail, name));
helper.setSubject(name +" GET IN TOUCH");
helper.setText(msg);
};
};
mailSender.send(preparator);
return "redirect:adminContact";
}
}
728x90