티스토리 뷰

자바/JAVA 입문

java 메일보내기

주년 2011. 10. 11. 14:11
출처: http://syh1011.tistory.com/tag/%EA%B5%AC%EA%B8%80%EB%A9%94%EC%9D%BC

메일보내기



import java.util.*;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;

public class TestEmailSender {
    private static final String emailHost = "smtp.gmail.com";
    private static final String emailId = "moyanada@gmail.com";
    private static final String emailPw = "ajtwoddl3";

    public void sendEmail(String from, String to, String subject, String content) {
        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", emailHost);
        props.put("mail.smtp.auth", "true");

        EmailAuthenticator authenticator = new EmailAuthenticator(emailId, emailPw);

        Session session = Session.getInstance(props, authenticator);

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

            msg.setSubject(subject);
            msg.setContent(content, "text/html; charset=EUC-KR");
            msg.setSentDate(new Date());
           
            /*// 파일을 첨부하는 예
            Multipart mp = new MimeMultipart();
            //mp.addBodyPart(mbp01);
            File file = new File("JavaMail_Append.java");
          
            MimeBodyPart mbp02 = new MimeBodyPart();

            FileDataSource fds = new FileDataSource(file);

            mbp02.setDataHandler(new DataHandler(fds));
            mbp02.setFileName(fds.getName());
            //String fileName = fds.getName(); //임시파일 삭제를 위해 파일이름을 설정

            mp.addBodyPart(mbp02);
            msg.setContent(mp);*/
           
            // create and fill the first message part
//            MimeBodyPart mbp1 = new MimeBodyPart();
//            mbp1.setText(msgText);
            String filename = "c://abc.xls";
            // create the second message part
            MimeBodyPart mbp2 = new MimeBodyPart();
           
            // attach the file to the message
            DataSource fds = new FileDataSource(filename);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());
           
            // create the Multipart and its parts to it
            Multipart mp = new MimeMultipart();
//            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);
           
            // add the Multipart to the message
            msg.setContent(mp);
           
            Transport.send(msg);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    class EmailAuthenticator extends Authenticator {
        private String id;
        private String pw;

        public EmailAuthenticator(String id, String pw) {
            this.id = id;
            this.pw = pw;
        }

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(id, pw);
        }
    }

    public static void main(String[] args) {
        String subject = "Gmail을 통한 Java Email 발송 테스트";
        String content = "Gmail을 통한 Java Email 발송 테스트입니다.";
        String from = "moyanada@naver.com";
        String to = "moyanada@naver.com";
        // 받을 이메일 주소는 반드시 ","로 구분해준다.

        new TestEmailSender().sendEmail(from, to, subject, content);
    }
}