사용자 도구

사이트 도구


wiki:java:메일_보내기

메일_보내기

  • description :
  • author : 도봉산핵주먹
  • email : hylee@repia.com
  • lastupdate : 2020-04-08

시작 전 확인사항

메일발송 시작 전 보낼메일 계정이 smtp 로 설정이 되어 있는지 확인해야 함.
네이버, 구글, outLook 계정 설정이 각각 다르기 때문에 찾아보고 해야함.
검색하면 무수히 많은 정보가 있으니 참고 하면 됨.

globals.properties (설정)

 #메일 발송을 위한 properties 지정
 # 보내는 메일
mail.senderId = ${보내는 사람 메일 주소}
 # 메일 서버
mail.host = ${메일 서버}
 # 메일 서버 port
mail.port = ${메일 서버 포트, 일반적으로 25}
 # 받는 메일
mail.addressee = ${받는 사람 메일 주소}

메일 계정 등록하는 방법

//'String consultTitle , String htmlDesc' mailSender메소스 들어오기전 title(제목)과 content(내용)을 넘겨준다.
    public static void mailSender(String consultTitle , String htmlDesc) throws AddressException, MessagingException, IOException {
	String senderId = EgovProperties.getProperty("mail.senderId");
	String host = EgovProperties.getProperty("mail.host");
	String port = EgovProperties.getProperty("mail.port");
	String addressee = EgovProperties.getProperty("mail.addressee");
 
	try {
		Properties props = new Properties();
 
		//SMTP 서버정보설정
		props.put("mail.smtp.host", host);
		props.put("mail.smtp.port", port);
		props.put("mail.smtp.starttls.enable", "true");
 
		//SMTP 서버정보를 session에 담는다.
		Session session = Session.getInstance(props);
 
		//보내는 메일 
		InternetAddress fromAddress = new InternetAddress(senderId);
 
		//MimeMessage 선언
		MimeMessage message = new MimeMessage(session);
 
		//보내는 메일 
		message.setFrom(fromAddress);
 
 
		// 내용 인코딩이 UTF-8일 떄 아래처럼 제목 인코딩도 'MimeUtility.encodeText(consultTitle, "UTF-8", "B")' 이렇게 선언해 줘야한다.
		// ex) message.setSubject(MimeUtility.encodeText(consultTitle, "UTF-8", "B"));
		// 위처럼 'MimeUtility.encodeText()'를 사용하면 catch에 'UnsupportedEncodingException eME'도 선언해줘야한다.
		// ex) catch (MessagingException | UnsupportedEncodingException eME)
 
		// 제목
		message.setSubject(consultTitle);
 
		//내용 ," 내용 인코딩 "
		message.setContent(htmlDesc, " text/html; charset=euc-kr");
 
		//본문이 html일 경우
		//또는
		//base64이미지 일경우 Header에 add 해줘야한다.
		message.addHeader("Content-Transfer-Encoding", "base64");
 
		//받는 메일
		InternetAddress toAddress = new InternetAddress(addressee);
		message.addRecipient(Message.RecipientType.TO, toAddress);
 
		//위에 정보를 담은 message를 Transport.send()로 메일보낸다.
		Transport.send(message);
	}
	catch (MessagingException eME)
	{
		Logger.error("MessagingException=[{}] - [{}][{}]", eME.getMessage(), host, port);
	}
    }

중요 내용

내용 인코딩이 UTF-8일 떄 제목 인코딩도 아래처럼 선언해야한다.
ex) message.setSubject(MimeUtility.encodeText(consultTitle, “UTF-8”, “B”));
'MimeUtility.encodeText()'를 사용하면 catch에 'UnsupportedEncodingException eME'도 선언해줘야한다.
ex) catch (MessagingException | UnsupportedEncodingException eME)

소스 출처

위 소스는 내부 프로젝트 3곳에서 검증이 되었습니다.
K * * (기관), 코 * * * * (기업), H * * * * (대학) 에 모두 적용된 것입니다.

Tip

Troubleshooting

Ref

/var/services/web/dokuwiki/data/pages/wiki/java/메일_보내기.txt · 마지막으로 수정됨: 2023/01/13 18:44 (바깥 편집)