한 번만 더 해보자

[Spring] 이메일 보내기 본문

Spring

[Spring] 이메일 보내기

정 하임 2023. 2. 18. 13:59
public boolean sendEmail() {
	String host = "smtp.gmail.com"; // 네이버일 경우 네이버 계정, gmail경우 gmail 계정 SMTP 서버 정보를 설정한다. 
	String user = "email@gmail.com"; // 이메일
	String password = "password"; // 비밀번호 

	Properties props = new Properties();
	props.put("mail.smtp.host", host);
	props.put("mail.smtp.port", 587); 
	props.put("mail.smtp.auth", "true");
	props.put("mail.smtp.starttls.enable", "true");//구글 로그인으로 바꾸면서 추가
	props.put("mail.smtp.ssl.protocols", "TLSv1.2");

	Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(user, password);
		}
	});

	try {
		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(user));
		message.addRecipient(Message.RecipientType.TO, new InternetAddress("email@gmail")); // 메일 보낼 곳
		message.setSubject("메일 제목"); // 메일 제목
		
		String tmpPwd = getRamdomPassword(13);

		String content = "<div>test</div>";

		message.setContent(content, "text/html; charset=utf-8");
		message.setSentDate(new Date());
		Transport.send(message);
		System.out.println("Success Message Send");

	} catch (MessagingException e) {
		e.printStackTrace();
		return false;
	}
	
	
	return true;
}
반응형