본문 바로가기

Java

Java에서 Mail 보내는 방법

https://mvnrepository.com/artifact/javax.mail/javax.mail-api/1.6.2

Maven이나 gradle로 다운을 받습니다.

 

	JavaMailSenderImpl getMailSender = new JavaMailSenderImpl();
		
        getMailSender.setHost("smtp.gmail.com");
        getMailSender.setPort(465);
        getMailSender.setUsername("이메일아이디");
        getMailSender.setPassword("패스워드");
        
        Properties javaMailProperties = new Properties();
        
        javaMailProperties.put("mail.smtp.auth", "true");
        javaMailProperties.put("mail.smtp.starttls.enable", "true");
        javaMailProperties.put("mail.smtp.ssl.trust", "smtp.gmail.com");
        javaMailProperties.put("mail.smtp.ssl.enable", "true");
        javaMailProperties.put("mail.transport.protocol", "smtp");
        javaMailProperties.put("mail.debug", "true");
 
        getMailSender.setJavaMailProperties(javaMailProperties);
		
        // 메일 제목
		final String subject = (String) mailInfo.get("title"); 
        // 머리말
		final String head = (String) mailInfo.get("head"); 
        // 메일 내용
		final String content = (String) mailInfo.get("body"); 
        // 참조자
		final String ref = (String) mailInfo.get("ref"); 
        // 꼬리말
		final String tail = (String) mailInfo.get("tail");
		// 발신자
		final String from = (String) mailInfo.get("fromEmail"); 
		// 수신자
		final String to = (String) mailInfo.get("toEmail"); 
		
		final HashMap<String, Object> tparam =  new HashMap<String,Object>();
		tparam.put("data", data);
		tparam.put("tableName", tblName);
		
		try {
			final ArrayList fileInfoList = new ArrayList<>();
			final MimeMessagePreparator preparator = new MimeMessagePreparator() {

				public void prepare(MimeMessage mimeMessage) throws Exception {
					String subPath = "cfileupload";
					String uploadPath = "";
					if(subPath.contains("../")|| subPath.contains("/") || subPath.contains("\\")) {
						subPath = subPath.replace("../", "").replace("/", "").replace("//", "");
						throw new Exception("file error");
					}
					if(File.separator.equals("\\")){
						uploadPath = fileUploadProperties.getProperty("WINsystem.uploadpath")+"\\"+subPath;
					}else{
						uploadPath = fileUploadProperties.getProperty("system.uploadpath")+File.separator+subPath;
					}
					
					// 멀티파트 메세지 허용
					final MimeMessageHelper mailHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
					// 발신자
					mailHelper.setFrom(from);
					// 수신자
					mailHelper.setTo(to);
					// 참조자
					if(ref != null || !ref.equals(""))
						mailHelper.setCc(ref);
					// 메일 제목
					mailHelper.setSubject(subject);
					// 메일 내용(html 허용)
					if(content != null && !content.equals("")&& tail != null && !tail.equals(""))
						mailHelper.setText(head+"<br/>"+content+"<br/>"+tail, true);
					else if(content != null && !content.equals(""))
						mailHelper.setText(head+"<br/>"+content, true);
					else if(tail != null && !tail.equals(""))
						mailHelper.setText(head+"<br/>"+tail, true);
					
					tparam.put("tf", true);
					
					if(contentService.getFilesn(tparam) != null && !contentService.getFilesn(tparam).equals("")) {
						final String filesn = contentService.getFilesn(tparam);
						final String[] tfilesn = filesn.split(",");
						ArrayList fileInfos = new ArrayList<>();
						fileInfos.add(0,uploadPath);
						for(int i = 0; i < tfilesn.length; i++) {
							tparam.put("file_sn", tfilesn[i]);
							HashMap<String,Object> content = contentService.getBlobfileInfo(tparam);
							byte[] contents = ((byte[])content.get("file"));
							String nm = contentService.getFilenm(tparam);
							tparam.put("nm", nm);
							FileUtils.writeByteArrayToFile(new File(uploadPath+ File.separator +nm), contents);
							// 파일 경로
							FileSystemResource file = new FileSystemResource(new File(uploadPath+ File.separator +nm));
							fileInfos.add(i+1,nm);
							// 업로드 파일 이름.형식
							mailHelper.addAttachment(nm, file);
						}
						fileInfoList.addAll(fileInfos);
					}
				}
			};
			getMailSender.send(preparator);
			//전송된 파일 삭제
			for(int i = 1; i < fileInfoList.size(); i++) {
				File dFile = new File(fileInfoList.get(0).toString(), fileInfoList.get(i).toString());
				dFile.delete();
			}
		} catch (Exception e) {
			log.info("메일 전송 실패" + e.toString());
			tparam.put("tf", false);
			return tparam;
		}

필요한 부분만 수정해서 가져다가 쓰시면 되겠습니다.

 

gmail은 구글계정 - 보안 - 보안 수준이 낮은 앱의 액세스 - 사용으로 바꿔줘야 합니다.

 

 

 

 

'Java' 카테고리의 다른 글

Ip 대역 검사 방법 2가지  (0) 2021.08.11
버튼 CSS(검색 창 같은)  (0) 2021.07.11
CKEditor 사용 시 html 태그가 그대로 출력 될 경우  (0) 2021.07.09
배열  (0) 2021.04.01
연산자  (0) 2021.03.31