1. 라이브러리
javax.mail javax.mail-api 1.6.2
2. 소스
import java.util.Date; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class MyMailSend { private String host; // host 네이버일 경우(smtp.naver.com), gmail경우(smtp.gmail.com) 로컬일 경우 localhost private String userId; // 아이디 private String password; // 비밀번호 public void emailSend(String fromEmail, String nickname, InternetAddress[] toEmail, String subject, String text, String contentType) { Properties props = System.getProperties(); props.put("mail.smtp.host", host); if (!host.equals("localhost")) { props.put("mail.smtp.host", host); props.put("mail.smtp.port", 465); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.ssl.enable", "true"); props.put("mail.smtp.ssl.trust", host); } Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userId, password); } }); MimeMessage msg = new MimeMessage(session); try { // 편지보낸시간 msg.setSentDate(new Date()); msg.setFrom(new InternetAddress(fromEmail, nickname)); // 이메일 수신자 //InternetAddress to = new InternetAddress(toEmail); //msg.setRecipient(Message.RecipientType.TO, to); msg.addRecipients(Message.RecipientType.TO, toEmail); // 이메일 제목 msg.setSubject(subject, "UTF-8"); // 이메일 내용 msg.setText(text, "UTF-8"); // 이메일 헤더 msg.setHeader("content-Type", contentType); // 메일보내기 javax.mail.Transport.send(msg, msg.getAllRecipients()); } catch (AddressException addr_e) { addr_e.printStackTrace(); } catch (MessagingException msg_e) { msg_e.printStackTrace(); } catch (Exception msg_e) { msg_e.printStackTrace(); } } public static void main(String[] args) { MyMailSend myMailSend = new MyMailSend(); myMailSend.host = "smtp.naver.com"; myMailSend.userId= "test@naver.com"; myMailSend.password = "1234"; //발신자 다른 주소나 별칭으로 메일 보내기 https://support.google.com/mail/answer/22370?hl=ko String fromEmail="test@naver.com"; //다중 메일 : 수신자 주소 InternetAddress[] addArray = new InternetAddress[1]; try { addArray[0] = new InternetAddress("test@gmail.com"); } catch (Exception e) { e.printStackTrace(); } myMailSend.emailSend(fromEmail, "홍길동기업", addArray, "메일제목", "메일내용", "text/html"); } }
1) gmail smtp 설정
https://privatenote.tistory.com/172
2)gmail 보안수준낮음 설정
Gmail smtp 사용할 경우 보안 수준이 낮은 앱 설정을 사용해야 한다.
아니면 구글에서 접근을 차단하기 때문
지메일 로그인 후 https://www.google.com/settings/security/lesssecureapps 접속해서 사용으로 선택한다.
3)gmail 다른 주소나 별칭으로 이메일 보내기
https://support.google.com/mail/answer/22370?hl=ko
4)naver 설정
https://m.blog.naver.com/monsterkn/221333152250
댓글 ( 6)
댓글 남기기