지구정복

[JAVA] 12/14 | 다이얼로그 콤보박스를 이용한 우편번호 검색기만들기, Java를 이용해서 이메일보내기(파일첨부하기) 본문

데이터 엔지니어링 정복/JAVA & JSP

[JAVA] 12/14 | 다이얼로그 콤보박스를 이용한 우편번호 검색기만들기, Java를 이용해서 이메일보내기(파일첨부하기)

eeaarrtthh 2020. 12. 15. 02:43
728x90
반응형

복습

1. Dialog = JFrame 자식창(종속창)
	* Modal(제어권)
	JColorChooser
	JFileChooser

2. MenuBar
	Menu / MenuItem

3. LayoutManager
	컨테이너별 기본 LayoutManager
	JFrame, JDialog	- BorderLayout
	JPanel		- FlowLayout
	* setLayout
	* AbsoulteLayout
	GridLayout
	CardLayout

4. Event
	1. Widget별로 각자 (Window에 친화적)
		XXXLister -> XXXEvent
		XXXAdapter -> XXXEvent
	2. Widget 통합
		구현을 통해서

 

실습 해답) 우편번호 검색기 (시, 구군, 동 콤보박스 만들고 검색되도록 하기)

 

프레임하나 만들고 프레임 속성중에 resizable을 꺼주면 실행시켰을 때 창을 임의로 조종할 수 없다.

그리고 아래와 같이 디자인한다.

 

다이얼로그 디자인을 아래와 같다.

 

그리고 콤보박스 3개 모두 이벤트를 준다. 그리고 ok와 cancle 버튼은 마우스 클릭이벤트를 준다.

Add Event Handler -> Item -> ItemStatedChanged

다이얼로그 창을 닫는 이벤트 코딩한다.

 

이제 DAO에서 콤보박스 3개(시도, 구군, 동), 리스트의 내용(시도, 구군, 동을 합친 주소)을 가져오기 위한 메서드 4개를 정의한다.

 

 

 

이제는 콤보박스 3개에 대한 모델을 만들고 그 안에 DAO에서 데이터를 받아와서 넣어야 한다.

 

콤보박스 3개에 대한 모델을 모두 만들었으면 이제 리스트 모델을 만든다.

 

최종 결과 소스코드는 아래와 같다.

-ZipcodeTO

package Pack1214_Model;

public class ZipcodeTO {
	private String zipcode;
	private String sido;
	private String gugun;
	private String dong;
	private String ri;
	private String bunji;

	public ZipcodeTO() {
		super();
	}
	


	public void setZipcode(String zipcode) {
		this.zipcode = zipcode;
	}

	public void setSido(String sido) {
		this.sido = sido;
	}

	public void setGugun(String gugun) {
		this.gugun = gugun;
	}

	public void setDong(String dong) {
		this.dong = dong;
	}

	public void setRi(String ri) {
		this.ri = ri;
	}

	public void setBunji(String bunji) {
		this.bunji = bunji;
	}

	public String getZipcode() {
		return zipcode;
	}

	public String getSido() {
		return sido;
	}

	public String getGugun() {
		return gugun;
	}

	public String getDong() {
		return dong;
	}

	public String getRi() {
		return ri;
	}

	public String getBunji() {
		return bunji;
	}
}

-ZipcodeDAO

package Pack1214_Model;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class ZipcodeDAO {
	
	private Connection conn;
	
	public ArrayList<ZipcodeTO> listSido() throws SQLException, ClassNotFoundException {
		ArrayList<ZipcodeTO> sidos = new ArrayList<ZipcodeTO>();
		
		//db 연결 정보
		String url = "jdbc:mysql://localhost:3307/sample";
		String user = "root";
		String password = "!123456";
		
		//db 드라이버 로딩
		Class.forName( "org.mariadb.jdbc.Driver" );
		this.conn = DriverManager.getConnection(url, user, password);
		
		//sql실행 및 sql결과 받아오기
		String sql = "select distinct sido from zipcode";
		PreparedStatement pstmt = this.conn.prepareStatement(sql);
		ResultSet rs = pstmt.executeQuery();
		while( rs.next() ) {
			ZipcodeTO to = new ZipcodeTO();
			to.setSido( rs.getString( "sido" ) ); 
			sidos.add( to ) ;
		}
		if( rs != null ) rs.close();
		if( pstmt != null ) pstmt.close();
		if( conn != null ) conn.close();
		
		return sidos;
	}
	
	public ArrayList<ZipcodeTO> listGugun( String strSido ) throws SQLException, ClassNotFoundException {
		ArrayList<ZipcodeTO> guguns = new ArrayList<ZipcodeTO>();
		
		//db 연결 정보
		String url = "jdbc:mysql://localhost:3307/sample";
		String user = "root";
		String password = "!123456";
		
		//db 드라이버 로딩
		Class.forName( "org.mariadb.jdbc.Driver" );
		this.conn = DriverManager.getConnection(url, user, password);
		
		//sql실행 및 sql결과 받아오기
		String sql = "select distinct gugun from zipcode where sido = ?";
		PreparedStatement pstmt = this.conn.prepareStatement(sql);
		pstmt.setString(1, strSido);
		ResultSet rs = pstmt.executeQuery();
		while( rs.next() ) {
			ZipcodeTO to = new ZipcodeTO();
			to.setGugun( rs.getString( "gugun" ) ); 
			guguns.add( to ) ;
		}
		if( rs != null ) rs.close();
		if( pstmt != null ) pstmt.close();
		if( conn != null ) conn.close();
		
		return guguns;
	}
	
	public ArrayList<ZipcodeTO> listDong( String strSido, String strGugun ) throws SQLException, ClassNotFoundException {
		ArrayList<ZipcodeTO> dongs = new ArrayList<ZipcodeTO>();
		
		//db 연결 정보
		String url = "jdbc:mysql://localhost:3307/sample";
		String user = "root";
		String password = "!123456";
		
		//db 드라이버 로딩
		Class.forName( "org.mariadb.jdbc.Driver" );
		this.conn = DriverManager.getConnection(url, user, password);
		
		//sql실행 및 sql결과 받아오기
		String sql = "select distinct dong from zipcode where sido = ? and gugun = ?";
		PreparedStatement pstmt = this.conn.prepareStatement(sql);
		pstmt.setString(1, strSido);
		pstmt.setString(2, strGugun);
		ResultSet rs = pstmt.executeQuery();
		while( rs.next() ) {
			ZipcodeTO to = new ZipcodeTO();
			to.setDong( rs.getString( "dong" ) ); 
			dongs.add( to ) ;
		}
		if( rs != null ) rs.close();
		if( pstmt != null ) pstmt.close();
		if( conn != null ) conn.close();
		
		return dongs;
	}
	

	public ArrayList<ZipcodeTO> listAddress( String strSido, String strGugun, String strDong ) throws SQLException, ClassNotFoundException {
			ArrayList<ZipcodeTO> addresses = new ArrayList<ZipcodeTO>();
			
			//db 연결 정보
			String url = "jdbc:mysql://localhost:3307/sample";
			String user = "root";
			String password = "!123456";
			
			//db 드라이버 로딩
			Class.forName( "org.mariadb.jdbc.Driver" );
			this.conn = DriverManager.getConnection(url, user, password);
			
			//sql실행 및 sql결과 받아오기
			String sql = "select zipcode, sido, gugun, dong, ri, bunji from zipcode where sido = ? and gugun = ? and dong = ?";
			PreparedStatement pstmt = this.conn.prepareStatement(sql);
			pstmt.setString(1, strSido );
			pstmt.setString(2, strGugun );
			pstmt.setString(3, strDong );
			ResultSet rs = pstmt.executeQuery();
			while( rs.next() ) {
				ZipcodeTO to = new ZipcodeTO();
				to.setZipcode( rs.getString( "zipcode" ) );
				to.setSido( rs.getString( "sido" ) );
				to.setGugun( rs.getString( "gugun" ) ); 
				to.setDong( rs.getString( "dong" ) ); 
				to.setRi( rs.getString( "ri" ) );
				to.setBunji( rs.getString( "bunji" ) );
				addresses.add( to ) ;
			}
			if( rs != null ) rs.close();
			if( pstmt != null ) pstmt.close();
			if( conn != null ) conn.close();
			
			return addresses;
	}
}

-SidoComboBoxModel

package Pack1214_Model;

import java.sql.SQLException;
import java.util.ArrayList;

import javax.swing.DefaultComboBoxModel;

public class SidoComboBoxModel extends DefaultComboBoxModel<String> {
	private ArrayList<ZipcodeTO> sidos;

	
	public SidoComboBoxModel() throws ClassNotFoundException, SQLException {
		ZipcodeDAO dao = new ZipcodeDAO();
		sidos = dao.listSido();
	}
	
	@Override
	public int getSize() {
		return sidos.size();
	}
	
	@Override
	public String getElementAt(int index) {
		ZipcodeTO to = sidos.get(index);
		return to.getSido();
	}
}

-GugunComboBoxModel

package Pack1214_Model;

import java.sql.SQLException;
import java.util.ArrayList;

import javax.swing.DefaultComboBoxModel;

public class GugunComboBoxModel extends DefaultComboBoxModel<String> {
	private ArrayList<ZipcodeTO> guguns;

	public GugunComboBoxModel( String strSido ) throws ClassNotFoundException, SQLException {
		ZipcodeDAO dao = new ZipcodeDAO();
		guguns = dao.listGugun( strSido );
	}

	@Override
	public int getSize() {
		// TODO Auto-generated method stub
		return guguns.size();
	}
	
	@Override
	public String getElementAt(int index) {
		ZipcodeTO to = guguns.get(index);
		return to.getGugun();
	}
}

-DongComboBoxModel

package Pack1214_Model;

import java.sql.SQLException;
import java.util.ArrayList;

import javax.swing.DefaultComboBoxModel;

public class DongComboBoxModel extends DefaultComboBoxModel<String> {
	private ArrayList<ZipcodeTO> dongs;

	public DongComboBoxModel( String strSido, String strGugun) throws ClassNotFoundException, SQLException {
		ZipcodeDAO dao = new ZipcodeDAO();
		dongs = dao.listDong( strSido, strGugun );
	}

	@Override
	public int getSize() {
		return dongs.size();
	}
	
	@Override
	public String getElementAt(int index) {
		ZipcodeTO to = dongs.get(index);
		return to.getDong();
	}
}

-AddressListModel

package Pack1214_Model;

import java.sql.SQLException;
import java.util.ArrayList;

import javax.swing.AbstractListModel;

public class AddressListModel extends AbstractListModel<String> {
	private ArrayList<ZipcodeTO> addresses;

	public AddressListModel( String strSido, String strGugun, String strDong) throws ClassNotFoundException, SQLException {
		ZipcodeDAO dao = new ZipcodeDAO();
		addresses = dao.listAddress(strSido, strGugun, strDong);
	}

	@Override
	public int getSize() {
		return addresses.size();
	}
	@Override
	public String getElementAt(int index) {
		ZipcodeTO to = addresses.get(index);
		String address = String.format("[%s] %s %s %s %s %s", 
				to.getZipcode(), to.getSido(), to.getGugun(), to.getDong(), 
				to.getRi(), to.getBunji() );
		return address;
	}
}

-SearchDialogUI

package Pack1214;

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import Pack1214_Model.AddressListModel;
import Pack1214_Model.DongComboBoxModel;
import Pack1214_Model.GugunComboBoxModel;
import Pack1214_Model.SidoComboBoxModel;
import Pack1214_Model.ZipcodeDAO;

import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;

public class SearchDialogUI extends JDialog {

	private final JPanel contentPanel = new JPanel();
	private JList list;
	private JComboBox comboBox1;
	private JComboBox comboBox2;
	private JComboBox comboBox3;

	/**
	 * Launch the application.
	 */
	/*
	public static void main(String[] args) {
		try {
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	*/

	/**
	 * Create the dialog.
	 * @throws SQLException 
	 * @throws ClassNotFoundException 
	 */
	public SearchDialogUI() throws ClassNotFoundException, SQLException {
		setBounds(100, 100, 450, 465);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(null);
		
		comboBox1 = new JComboBox();
		comboBox1.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent arg0) {
				if ( arg0.getStateChange() == ItemEvent.SELECTED ) {
					//System.out.println( (String)comboBox1.getSelectedItem() );
					try {
						comboBox2.setModel( new GugunComboBoxModel( (String)comboBox1.getSelectedItem() ) );
						
					} catch (ClassNotFoundException | SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
		comboBox1.setBounds(12, 10, 115, 23);
		contentPanel.add(comboBox1);
		
		comboBox2 = new JComboBox();
		comboBox2.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent arg1) {
				if ( arg1.getStateChange() == ItemEvent.SELECTED ) {
					try {
						comboBox3.setModel( new DongComboBoxModel( (String)comboBox1.getSelectedItem(), (String)comboBox2.getSelectedItem() ) );
					} catch (ClassNotFoundException | SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
		comboBox2.setBounds(139, 10, 115, 23);
		contentPanel.add(comboBox2);
		
		comboBox3 = new JComboBox();
		comboBox3.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent arg2) {
				if ( arg2.getStateChange() == ItemEvent.SELECTED ) {
					try {
						list.setModel( new AddressListModel( 
								(String)comboBox1.getSelectedItem(), (String)comboBox2.getSelectedItem(), (String)comboBox3.getSelectedItem()));
					} catch (ClassNotFoundException | SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
		comboBox3.setBounds(266, 10, 115, 23);
		contentPanel.add(comboBox3);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scrollPane.setBounds(12, 60, 410, 323);
		contentPanel.add(scrollPane);
		
		list = new JList();
		scrollPane.setViewportView(list);
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
		{
			JButton okButton = new JButton("OK");
			okButton.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent e) {
					SearchDialogUI.this.dispose();
				}
			});
			okButton.setActionCommand("OK");
			buttonPane.add(okButton);
			getRootPane().setDefaultButton(okButton);
		}
		{
			JButton cancelButton = new JButton("Cancel");
			cancelButton.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent e) {
					SearchDialogUI.this.dispose();
				}
			});
			cancelButton.setActionCommand("Cancel");
			buttonPane.add(cancelButton);
		}
		}
		
		//초기 시도 데이터 입력
		comboBox1.setModel( new SidoComboBoxModel() );
	}
	
	public String getAddress() {
		return (String)list.getSelectedValue();
	}
}

-ZipcodeSearchUIEx01

package Pack1214;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JDialog;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;

public class ZipcodeSearchUIEx01 extends JFrame {

	private JPanel contentPane;
	private JTextField textField1;
	private JTextField textField2;
	private JTextField textField3;
	private JTextField textField4;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ZipcodeSearchUIEx01 frame = new ZipcodeSearchUIEx01();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public ZipcodeSearchUIEx01() {
		setResizable(false);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 594, 471);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		textField1 = new JTextField();
		textField1.setEditable(false);
		textField1.setBounds(12, 10, 116, 21);
		contentPane.add(textField1);
		textField1.setColumns(10);
		
		textField2 = new JTextField();
		textField2.setEditable(false);
		textField2.setColumns(10);
		textField2.setBounds(140, 10, 116, 21);
		contentPane.add(textField2);
		
		JButton btn = new JButton("\uC6B0\uD3B8\uBC88\uD638 \uAC80\uC0C9");
		btn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				SearchDialogUI dialog;
				try {
					dialog = new SearchDialogUI();
					dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
					dialog.setModal(true);
					dialog.setVisible(true);
					String address = dialog.getAddress();
					if ( address != null ) {
						String[] addresses = address.split("]");
						textField3.setText( addresses[1] );
						String zipcode = addresses[0].replaceAll("\\[", "");
						String[] zipcodes = zipcode.split("-");
						textField1.setText( zipcodes[0] );
						textField2.setText( zipcodes[1] );
					}
				} catch (ClassNotFoundException | SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

			}
			
		});
		btn.setBounds(285, 9, 147, 23);
		contentPane.add(btn);
		
		textField3 = new JTextField();
		textField3.setEditable(false);
		textField3.setColumns(10);
		textField3.setBounds(12, 41, 554, 21);
		contentPane.add(textField3);
		
		textField4 = new JTextField();
		textField4.setColumns(10);
		textField4.setBounds(12, 72, 554, 21);
		contentPane.add(textField4);
	}
}

-최종결과

 

 

ㅇ Java를 이용해서 메일보내기

메일보내기(스팸)

메일을 작성하면 나의 메일서버로 가고 이게 상대방의 메일서버로 간 뒤 상대방이 메일을 읽는다.
메일작성 -> 나의 메일서버 -> 상대방의 메일서버 -> 상대방메일

메일서버의 프로토콜: smtp(Simple Mail Transfer Protocol)


이제 Java로 Google 메일서버를 이용해서 다른 곳으로 메일을 보낼 것이다.

먼저 구글의 보안등급을 하향시켜야 한다.
아래 사이트에 들어간 뒤 
'보안 수준이 낮은 앱의 액세스' 를 허용시킨다.

 

www.google.com/settings/security/lesssecureapps  

 

메일 서버를 사용하려면 2가지의 라이브러리가 필요하다.

activation.jar
0.05MB

 

 

mail.jar
0.50MB

 

 

 

이를 자바 워크스페이스 apis 폴더에 집어넣는다.

 

이제 새로운 프로젝트를 두 개의 api를 포함시켜서 만든다.

 

새로운 클래스를 Authenticator 를 상속받아서 만든다.

코드는 아래와 같다.

package Pack1214_1;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class MyAuthenticator extends Authenticator {
	private String fromMail;
	private String fromPassword;
	
	public MyAuthenticator(String fromMail, String fromPassword) {
		this.fromMail = fromMail;
		this.fromPassword = fromPassword;
	}
	
	@Override
	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(fromMail, fromPassword);
	}
	
}

-실행클래스

package Pack1214_1;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailSender {
	private String fromMail;
	private String fromPassword;
	
	public MailSender() {
		this.fromMail = "자신의 구글이메일 주소";
		this.fromPassword = "자신의 구글 이메일 비밀번호";
	}
	
	public static void main(String[] args) {
		String toMail = "받는사람의 이메일주소";
		String toName = "tester";
		String subject = "title";
		String content = "hahahah";
		
		MailSender mailSender = new MailSender();
		mailSender.sendMail(toMail, toName, subject, content);
	}
	
	//메일 보내는 메서드
	public void sendMail( String toMail, String toName, String subject, String content ) {
		try {
			//구글 smtp 서버 설정하기
			Properties props = new Properties();
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.transport.protocol", "smtp");
			props.put("mail.smtp.host", "smtp.gmail.com");
			props.put("mail.smtp.port", "465");
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			
			//인증환경 설정
			MyAuthenticator authenticator = new MyAuthenticator( fromMail, fromPassword );
			
			//접속후 연결환경 설정
			Session session = Session.getDefaultInstance(props, authenticator);
			
			//보낼 메일 내용
			MimeMessage msg = new MimeMessage( session );
			
			//전체적인 설정
			//text/plain: 내용의 형태(plain은 평서문을 의미, charset=utf-8는 인코딩
			msg.setHeader( "Content-Type", "text/plain; charset=utf-8");
			//받는 사람에 대한 설정
			msg.addRecipient( Message.RecipientType.TO, new InternetAddress( toMail, toName, "utf-8") );
			//제목
			msg.setSubject(subject);
			//내용
			msg.setContent( content, "text/plain; charset=utf-8");
			//전송하는 시간 설정
			msg.setSentDate( new java.util.Date() );
			//메시지 보내기
			Transport.send(msg);
			
			System.out.println( "전송완료" );
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
}

-결과

 

 

이번에는 내용을 보내는 부분에 이미지나 다른 정보를 전송해보자.

즉 html문서를 전송해보자.

아래와 같이 작성하면된다.

content에 html 문서 작성하고

설정하는 곳에서 text/html로 바꿔준다.

package Pack1214_1;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailSender2 {
	private String fromMail;
	private String fromPassword;
	
	public MailSender2() {
		this.fromMail = "hoeeyz1@gmail.com";
		this.fromPassword = "******";
	}
	
	public static void main(String[] args) {
		String toMail = "hoeeyz1@gmail.com";
		String toName = "tester";
		String subject = "title";
		String content = 
		"<html><head><meta charset='utf-8'/></head><body><font color='blue'>html 내용</font></body></html>";
		
		
		MailSender mailSender = new MailSender();
		mailSender.sendMail(toMail, toName, subject, content);
	}
	
	//메일 보내는 메서드
	public void sendMail( String toMail, String toName, String subject, String content ) {
		try {
			//구글 smtp 서버 설정하기
			Properties props = new Properties();
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.transport.protocol", "smtp");
			props.put("mail.smtp.host", "smtp.gmail.com");
			props.put("mail.smtp.port", "465");
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			
			//인증환경 설정
			MyAuthenticator authenticator = new MyAuthenticator( fromMail, fromPassword );
			
			//접속후 연결환경 설정
			Session session = Session.getDefaultInstance(props, authenticator);
			
			//보낼 메일 내용
			MimeMessage msg = new MimeMessage( session );
			
			//전체적인 설정
			//text/plain: 내용의 형태(plain은 평서문을 의미, charset=utf-8는 인코딩
			msg.setHeader( "Content-Type", "text/html; charset=utf-8");
			//받는 사람에 대한 설정
			msg.addRecipient( Message.RecipientType.TO, new InternetAddress( toMail, toName, "utf-8") );
			//제목
			msg.setSubject(subject);
			//내용
			msg.setContent( content, "text/html; charset=utf-8");
			//전송하는 시간 설정
			msg.setSentDate( new java.util.Date() );
			//메시지 보내기
			Transport.send(msg); 
			
			System.out.println( "전송완료" );
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
}

 

이번에는 아무 이미지주소를 복사해서 아래와 같이 content 내용을 바꿔준다.

String content = 
		"<html><head><meta charset='utf-8'/></head><body><font color='blue'>html 내용</font><br><img src='https://search.pstatic.net/common/?src=http%3A%2F%2Fcafefiles.naver.net%2FMjAyMDA3MjZfMTcy%2FMDAxNTk1NzMxMTUxODEw.6LgIIZEmM7ZLuIouGggl0upVu7dZvl9D05XfVZ69AYEg.kZT5juWhWKn3NUf3egb8of-6DGUseqZ-0N8TeUa0ElIg.JPEG%2F%25C4%25A1%25B8%25C5%25BA%25B8%25C7%25E8%25BB%25F3%25C7%25B01.jpg&type=sc960_832'></body></html>";

실습)

이메일을 전송할 수 있는 프레임을 만들어보자.

아래와 같이 만들어보자.

-MyAuthenticator

package Pack1214_2;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class MyAuthenticator extends Authenticator {
	private String fromMail;
	private String fromPassword;
	
	public MyAuthenticator(String fromMail, String fromPassword) {
		this.fromMail = fromMail;
		this.fromPassword = fromPassword;
	}
	
	@Override
	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(fromMail, fromPassword);
	}
}

-MailSender

package Pack1214_2;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import Pack1214_1.MyAuthenticator;

public class MailSender {
	private String fromMail;
	private String fromPassword;
	
	public MailSender() {
		this.fromMail = "자신의 보낼 구글이메일";
		this.fromPassword = "자신의 구글이메일 비밀번호";
	}
	
		//text 메일 보내는 메서드
		public void sendMailText( String toMail, String toName, String subject, String content ) {
			try {
				//구글 smtp 서버 설정하기
				Properties props = new Properties();
				props.put("mail.smtp.starttls.enable", "true");
				props.put("mail.transport.protocol", "smtp");
				props.put("mail.smtp.host", "smtp.gmail.com");
				props.put("mail.smtp.port", "465");
				props.put("mail.smtp.auth", "true");
				props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
				
				//인증환경 설정
				MyAuthenticator authenticator = new MyAuthenticator( fromMail, fromPassword );
				
				//접속후 연결환경 설정
				Session session = Session.getDefaultInstance(props, authenticator);
				
				//보낼 메일 내용
				MimeMessage msg = new MimeMessage( session );
				
				//전체적인 설정
				//text/plain: 내용의 형태(plain은 평서문을 의미, charset=utf-8는 인코딩
				msg.setHeader( "Content-Type", "text/plain; charset=utf-8");
				//받는 사람에 대한 설정
				msg.addRecipient( Message.RecipientType.TO, new InternetAddress( toMail, toName, "utf-8") );
				//제목
				msg.setSubject(subject);
				//내용
				msg.setContent( content, "text/plain; charset=utf-8");
				//전송하는 시간 설정
				msg.setSentDate( new java.util.Date() );
				//메시지 보내기
				Transport.send(msg);
				
				System.out.println( "전송완료" );
				
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (MessagingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
		}
		
		//html 메일 보내는 메서드
		public void sendMailHtml( String toMail, String toName, String subject, String content ) {
			try {
				//구글 smtp 서버 설정하기
				Properties props = new Properties();
				props.put("mail.smtp.starttls.enable", "true");
				props.put("mail.transport.protocol", "smtp");
				props.put("mail.smtp.host", "smtp.gmail.com");
				props.put("mail.smtp.port", "465");
				props.put("mail.smtp.auth", "true");
				props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
				
				//인증환경 설정
				MyAuthenticator authenticator = new MyAuthenticator( fromMail, fromPassword );
				
				//접속후 연결환경 설정
				Session session = Session.getDefaultInstance(props, authenticator);
				
				//보낼 메일 내용
				MimeMessage msg = new MimeMessage( session );
				
				//전체적인 설정
				//text/plain: 내용의 형태(plain은 평서문을 의미, charset=utf-8는 인코딩
				msg.setHeader( "Content-Type", "text/html; charset=utf-8");
				//받는 사람에 대한 설정
				msg.addRecipient( Message.RecipientType.TO, new InternetAddress( toMail, toName, "utf-8") );
				//제목
				msg.setSubject(subject);
				//내용
				msg.setContent( content, "text/html; charset=utf-8");
				//전송하는 시간 설정
				msg.setSentDate( new java.util.Date() );
				//메시지 보내기
				Transport.send(msg);
				
				System.out.println( "전송완료" );
				
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (MessagingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
		}
}

-MailUI

package Pack1214_2;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.ButtonGroup;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class MailUI extends JFrame {

	private JPanel contentPane;
	private JTextField textField1;
	private JTextField textField2;
	private JTextArea textArea;
	private final ButtonGroup buttonGroup = new ButtonGroup();
	private JRadioButton rd2;
	private JRadioButton rd1;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MailUI frame = new MailUI();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public MailUI() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 623, 500);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JLabel lblNewLabel = new JLabel("\uBC1B\uC744 \uC8FC\uC18C");
		lblNewLabel.setBounds(12, 10, 70, 15);
		contentPane.add(lblNewLabel);
		
		JLabel lblNewLabel_1 = new JLabel("\uC81C \uBAA9");
		lblNewLabel_1.setBounds(22, 44, 70, 15);
		contentPane.add(lblNewLabel_1);
		
		textField1 = new JTextField();
		textField1.setBounds(94, 7, 501, 21);
		contentPane.add(textField1);
		textField1.setColumns(10);
		
		textField2 = new JTextField();
		textField2.setColumns(10);
		textField2.setBounds(94, 41, 501, 21);
		contentPane.add(textField2);
		
		rd1 = new JRadioButton("HTML");
		rd1.setSelected(true);
		buttonGroup.add(rd1);
		rd1.setBounds(94, 80, 121, 23);
		contentPane.add(rd1);
		
		rd2 = new JRadioButton("TEXT");
		buttonGroup.add(rd2);
		rd2.setBounds(219, 80, 121, 23);
		contentPane.add(rd2);
		
		JLabel lblNewLabel_2 = new JLabel("\uBCF4\uB0B4\uB294 \uB0B4\uC6A9");
		lblNewLabel_2.setBounds(12, 126, 70, 15);
		contentPane.add(lblNewLabel_2);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(12, 148, 583, 249);
		contentPane.add(scrollPane);
		
		textArea = new JTextArea();
		scrollPane.setViewportView(textArea);
		
		JButton btnNewButton = new JButton("\uBA54\uC77C\uC804\uC1A1");
		btnNewButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				String toMail = textField1.getText();
				String toName = "tester";
				String subject = textField2.getText();
				String content = textArea.getText();
				
				MailSender mailSender = new MailSender();
				if ( rd1.isSelected() ) {
					mailSender.sendMailHtml(toMail, toName, subject, content);
				} else if ( rd2.isSelected() ) {
					mailSender.sendMailText(toMail, toName, subject, content);
				}
			}
		});
		btnNewButton.setBounds(498, 416, 97, 23);
		contentPane.add(btnNewButton);
	}
}

-실행결과

 

실습)

이번에는 첨부파일을 보내도록 만들어보자. 

디자인 예시는 아래와 같다.

 

-MyAuthenticator

package Pack1214_2;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class MyAuthenticator extends Authenticator {
	private String fromMail;
	private String fromPassword;
	
	public MyAuthenticator(String fromMail, String fromPassword) {
		this.fromMail = fromMail;
		this.fromPassword = fromPassword;
	}
	
	@Override
	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(fromMail, fromPassword);
	}
}

-MailSender

package Pack1214_2;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import Pack1214_1.MyAuthenticator;

public class MailSender {
	private String fromMail;
	private String fromPassword;
	
	public MailSender() {
		this.fromMail = "hoeeyz1@gmail.com";
		this.fromPassword = "**********";
	}
	
	//text 메일 보내는 메서드
	public void sendMailText( String toMail, String toName, String subject, String content ) {
		try {
			//구글 smtp 서버 설정하기
			Properties props = new Properties();
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.transport.protocol", "smtp");
			props.put("mail.smtp.host", "smtp.gmail.com");
			props.put("mail.smtp.port", "465");
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			
			//인증환경 설정
			MyAuthenticator authenticator = new MyAuthenticator( fromMail, fromPassword );
			
			//접속후 연결환경 설정
			Session session = Session.getDefaultInstance(props, authenticator);
			
			//보낼 메일 내용
			MimeMessage msg = new MimeMessage( session );
			
			//전체적인 설정
			//text/plain: 내용의 형태(plain은 평서문을 의미, charset=utf-8는 인코딩
			msg.setHeader( "Content-Type", "text/plain; charset=utf-8");
			//받는 사람에 대한 설정
			msg.addRecipient( Message.RecipientType.TO, new InternetAddress( toMail, toName, "utf-8") );
			//제목
			msg.setSubject(subject);
			//내용
			msg.setContent( content, "text/plain; charset=utf-8");
			//전송하는 시간 설정
			msg.setSentDate( new java.util.Date() );
			//메시지 보내기
			Transport.send(msg);
			
			System.out.println( "전송완료" );
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	
	//text + file 메일 보내는 메서드
	public void sendMailTextFile( String toMail, String toName, String subject, String content, File fileName ) {
		try {
			//구글 smtp 서버 설정하기
			Properties props = new Properties();
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.transport.protocol", "smtp");
			props.put("mail.smtp.host", "smtp.gmail.com");
			props.put("mail.smtp.port", "465");
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			
			//인증환경 설정
			MyAuthenticator authenticator = new MyAuthenticator( fromMail, fromPassword );
			
			//접속후 연결환경 설정
			Session session = Session.getDefaultInstance(props, authenticator);
			
			//보낼 메일 내용
			MimeMessage msg = new MimeMessage( session );
			
			//전체적인 설정
			//text/plain: 내용의 형태(plain은 평서문을 의미, charset=utf-8는 인코딩
			msg.setHeader( "Content-Type", "text/plain; charset=utf-8");
			//받는 사람에 대한 설정
			msg.addRecipient( Message.RecipientType.TO, new InternetAddress( toMail, toName, "utf-8") );
			//제목
			msg.setSubject(subject);
			
			//내용 첨가하기
			MimeBodyPart mbp1 = new MimeBodyPart();
			mbp1.setText(content, "utf-8", "plain");
			
			//파일첨부하기
			MimeBodyPart mbp2 = new MimeBodyPart();
			FileDataSource fds = new FileDataSource( fileName.getAbsolutePath() );
			mbp2.setDataHandler( new DataHandler(fds ) );
			mbp2.setFileName( fds.getName() );
			
			Multipart mp = new MimeMultipart();
			mp.addBodyPart(mbp1);
			mp.addBodyPart(mbp2);
			msg.setContent(mp);
			
			//전송하는 시간 설정
			msg.setSentDate( new java.util.Date() );
			//메시지 보내기
			Transport.send(msg);
			
			System.out.println( "전송완료" );
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			System.out.println( "메일 안감" + e.getMessage() );
		}
	}
	
	
	//html 메일 보내는 메서드
	public void sendMailHtml( String toMail, String toName, String subject, String content ) {
		try {
			//구글 smtp 서버 설정하기
			Properties props = new Properties();
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.transport.protocol", "smtp");
			props.put("mail.smtp.host", "smtp.gmail.com");
			props.put("mail.smtp.port", "465");
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			
			//인증환경 설정
			MyAuthenticator authenticator = new MyAuthenticator( fromMail, fromPassword );
			
			//접속후 연결환경 설정
			Session session = Session.getDefaultInstance(props, authenticator);
			
			//보낼 메일 내용
			MimeMessage msg = new MimeMessage( session );
			
			//전체적인 설정
			//text/plain: 내용의 형태(plain은 평서문을 의미, charset=utf-8는 인코딩
			msg.setHeader( "Content-Type", "text/html; charset=utf-8");
			//받는 사람에 대한 설정
			msg.addRecipient( Message.RecipientType.TO, new InternetAddress( toMail, toName, "utf-8") );
			//제목
			msg.setSubject(subject);
			//내용
			msg.setContent( content, "text/html; charset=utf-8");
			//전송하는 시간 설정
			msg.setSentDate( new java.util.Date() );
			//메시지 보내기
			Transport.send(msg);
			
			System.out.println( "전송완료" );
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	
	//html + file 메일 보내는 메서드
	public void sendMailHtmlFile( String toMail, String toName, String subject, String content, File fileName ) {
		try {
			//구글 smtp 서버 설정하기
			Properties props = new Properties();
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.transport.protocol", "smtp");
			props.put("mail.smtp.host", "smtp.gmail.com");
			props.put("mail.smtp.port", "465");
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			
			//인증환경 설정
			MyAuthenticator authenticator = new MyAuthenticator( fromMail, fromPassword );
			
			//접속후 연결환경 설정
			Session session = Session.getDefaultInstance(props, authenticator);
			
			//보낼 메일 내용
			MimeMessage msg = new MimeMessage( session );
			
			//전체적인 설정
			//text/plain: 내용의 형태(plain은 평서문을 의미, charset=utf-8는 인코딩
			msg.setHeader( "Content-Type", "text/html; charset=utf-8");
			//받는 사람에 대한 설정
			msg.addRecipient( Message.RecipientType.TO, new InternetAddress( toMail, toName, "utf-8") );
			//제목
			msg.setSubject(subject);
			//내용 첨가하기
			MimeBodyPart mbp1 = new MimeBodyPart();
			mbp1.setText(content, "utf-8", "html");
			
			
			//파일첨부하기
			MimeBodyPart mbp2 = new MimeBodyPart();
			FileDataSource fds = new FileDataSource( fileName.getAbsolutePath() );
			mbp2.setDataHandler( new DataHandler(fds ) );
			mbp2.setFileName( fds.getName() );
			
			Multipart mp = new MimeMultipart();
			mp.addBodyPart(mbp1);
			mp.addBodyPart(mbp2);
			msg.setContent(mp, "text/html; charset=utf-8");
			
			//전송하는 시간 설정
			msg.setSentDate( new java.util.Date() );
			//메시지 보내기
			Transport.send(msg);
			
			System.out.println( "전송완료" );
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
}

-MailUI

package Pack1214_2;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JScrollPane;
import javax.activation.FileDataSource;
import javax.mail.MessagingException;
import javax.swing.ButtonGroup;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.UnsupportedEncodingException;

public class MailUI extends JFrame {

	private JPanel contentPane;
	private JTextField textField1;
	private JTextField textField2;
	private JTextArea textArea;
	private final ButtonGroup buttonGroup = new ButtonGroup();
	private JRadioButton rd2;
	private JRadioButton rd1;
	private JLabel lblNewLabel_3;
	private JLabel lblNewLabel_4;
	private JTextField textField3;
	private JButton btn2;
	
	JFileChooser fileChooser = new JFileChooser();
	File fileName;
	
	String toMail;
	String toName = "tester";
	String subject;
	String content;
	
	MailSender mailSender = new MailSender();
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MailUI frame = new MailUI();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public MailUI() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 623, 500);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JLabel lblNewLabel = new JLabel("\uBC1B\uC744 \uC8FC\uC18C");
		lblNewLabel.setBounds(12, 10, 70, 15);
		contentPane.add(lblNewLabel);
		
		JLabel lblNewLabel_1 = new JLabel("\uC81C \uBAA9");
		lblNewLabel_1.setBounds(22, 44, 70, 15);
		contentPane.add(lblNewLabel_1);
		
		textField1 = new JTextField();
		textField1.setBounds(94, 7, 501, 21);
		contentPane.add(textField1);
		textField1.setColumns(10);
		
		textField2 = new JTextField();
		textField2.setColumns(10);
		textField2.setBounds(94, 41, 501, 21);
		contentPane.add(textField2);
		
		rd1 = new JRadioButton("HTML");
		rd1.setSelected(true);
		buttonGroup.add(rd1);
		rd1.setBounds(94, 80, 121, 23);
		contentPane.add(rd1);
		
		rd2 = new JRadioButton("TEXT");
		buttonGroup.add(rd2);
		rd2.setBounds(219, 80, 121, 23);
		contentPane.add(rd2);
		
		JLabel lblNewLabel_2 = new JLabel("\uBCF4\uB0B4\uB294 \uB0B4\uC6A9");
		lblNewLabel_2.setBounds(12, 126, 70, 15);
		contentPane.add(lblNewLabel_2);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(12, 148, 583, 200);
		contentPane.add(scrollPane);
		
		textArea = new JTextArea();
		scrollPane.setViewportView(textArea);
		
		btn2 = new JButton("\uD30C\uC77C \uCC3E\uAE30");
		btn2.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				int result = fileChooser.showOpenDialog( MailUI.this );
				if ( result == JFileChooser.APPROVE_OPTION ) {
					fileName = fileChooser.getSelectedFile();
					textField3.setText( fileName.getName() );
				}
			}
		});
		btn2.setBounds(498, 368, 97, 23);
		contentPane.add(btn2);
		
		JButton btn1 = new JButton("\uBA54\uC77C\uC804\uC1A1");
		btn1.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				toMail = textField1.getText();
				subject = textField2.getText();
				content = textArea.getText();
				
				if ( rd1.isSelected() ) {
					if ( fileChooser.getSelectedFile() != null ) {
						mailSender.sendMailHtmlFile(toMail, toName, subject, content, fileName);
					} else {
						mailSender.sendMailHtml(toMail, toName, subject, content);
					}

				} else if ( rd2.isSelected() ) {
					if ( fileChooser.getSelectedFile() != null ) {
						mailSender.sendMailTextFile(toMail, toName, subject, content, fileName);
					} else {
						mailSender.sendMailText(toMail, toName, subject, content);
					}
				} 

			}
		});
		btn1.setBounds(498, 416, 97, 23);
		contentPane.add(btn1);
		
		lblNewLabel_3 = new JLabel("\uD615 \uC2DD");
		lblNewLabel_3.setBounds(22, 84, 51, 15);
		contentPane.add(lblNewLabel_3);
		
		lblNewLabel_4 = new JLabel("\uD30C\uC77C \uCCA8\uBD80");
		lblNewLabel_4.setBounds(12, 372, 70, 15);
		contentPane.add(lblNewLabel_4);
		
		textField3 = new JTextField();
		textField3.setEditable(false);
		textField3.setBounds(94, 369, 384, 21);
		contentPane.add(textField3);
		textField3.setColumns(10);
	}
}

 

-실행결과

먼저 text 형식으로 보내보자.

 

html문서로 보내보자.

728x90
반응형
Comments