Java로 SMTP 메일 발송하기
2024. 11. 19. 22:58ㆍJava
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
application.properties
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=your-email@gmail.com
spring.mail.password=your-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
Email Service
package com.example.email;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
@Service
public class EmailService {
@Autowired
private JavaMailSender mailSender;
public void sendEmail(String to, String subject, String body) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(body);
message.setFrom("your-email@gmail.com"); // Replace with your email
mailSender.send(message);
}
public void sendHtmlEmail(String to, String subject, String htmlBody) throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(htmlBody, true); // Set 'true' for HTML content
helper.setFrom("your-email@gmail.com"); // Replace with your email
mailSender.send(mimeMessage);
}
}
Email Controller
package com.example.email;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EmailController {
@Autowired
private EmailService emailService;
@GetMapping("/send-email")
public String sendEmail(@RequestParam String to, @RequestParam String subject, @RequestParam String body) {
emailService.sendEmail(to, subject, body);
return "Email sent successfully!";
}
}
Test
http://localhost:8080/send-email?to=recipient-email@gmail.com&subject=Test&body=Hello!
'Java' 카테고리의 다른 글
Java Directory 존재여부 체크 및 생성 (0) | 2024.11.30 |
---|---|
Java 정규식으로 replace 하기 (0) | 2024.11.26 |
숫자 6자리 임시 비밀번호 만들기 (0) | 2024.11.19 |
깨진 Hex Code decode 하기 (0) | 2024.11.17 |
List<Map<String, Object>>에 item 추가하기 (1) | 2024.11.12 |