Site Search :
Standard Enterprise XML Methodology Pattern Setting Tunning Other
Article Contributors
GuestBook
Javapattern Maven
XSourceGen Dev
JetSpeed Test
JLook Image
jLook Family Site


Java WebMail System Implementation(4)
 
첨부파일의 메일보내기 및 POP3서버의 폴더내용을 이용하여 데이터를 가져오도록 하는 샘플을 설명과 함께 보도록 하자. ( 2003/05/13 ) 684
Written by ienvyou - 최지웅
2 of 4
 
File Attatchment Mail Source Code


Source Code : 



import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.mail.event.*;

public class sendfile  implements ConnectionListener, TransportListener{

    public static void main(String[] args) {
            if (args.length != 5) {
                System.out.println("usage: java sendfile <to> <from> <smtp> <file> true|false");
                System.exit(1);
            }

            String to = args[0];
            String from = args[1];
            String host = args[2];
            String filename = args[3];
            String bcc = "ienvyou@javapattern.info";
            boolean debug = Boolean.valueOf(args[4]).booleanValue();
            String msgText1 = "보내졌습니까?\n";
            String subject = "파일보내기 예제";
            
            // create some properties and get the default Session
            Properties props = System.getProperties();
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.auth" , "true"); //아주 중요 없으면 인증을 시도할수가 없다.
            
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(debug);
            
            sendfile sf = new sendfile();
            sf.go(session, to, bcc, from, subject, msgText1, filename );
    }

    public void go(Session session, 
                        String to, 
                        String bccc, 
                        String from, 
                        String subject, 
                        String msgText1, 
                        String filename){
            Transport trans = null;
            try {
                // create a message
                MimeMessage msg = new MimeMessage(session);
                msg.setFrom(new InternetAddress(from));
                InternetAddress[] address = {new InternetAddress(to)};
                InternetAddress [] cc = {new InternetAddress("ienvyou@javapattern.info")};
                InternetAddress [] bcc = {new InternetAddress("ienvyou@javapattern.info")};
                msg.setRecipients(Message.RecipientType.TO, address);
                msg.setRecipients(Message.RecipientType.CC, cc);
                msg.setRecipients(Message.RecipientType.BCC, bcc);
                msg.setSubject(subject);

                // create and fill the first message part
                MimeBodyPart mbp1 = new MimeBodyPart();
                mbp1.setText(msgText1);

                // create the second message part
                MimeBodyPart mbp2 = new MimeBodyPart();

                    // attach the file to the message
                FileDataSource fds = new FileDataSource(filename);

                mbp2.setDataHandler(new DataHandler(fds));
            // 헤더에 파일이름을 세팅할때 base64형태로 반드시.
                mbp2.setFileName(MimeUtility.encodeText(fds.getName(), "euc-kr","B"));  

                // 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);

                // set the Date: header
                msg.setSentDate(new Date());
                
        /************** Carouser Adding *************************************/
                msg.saveChanges(); // msg객체에서 데이터를 보낼수 있도록 속성변경

                // 인증을 시도하도록 한다.
                trans = session.getTransport(address[0]);

                // register ourselves as listener for ConnectionEvents 
                // and TransportEvents
                trans.addConnectionListener(this);
                trans.addTransportListener(this);


                 // connect the transport
                trans.connect("openitech.co.kr","ienvyou","0000");
               

                // send the message
                //Transport.send(msg);
                trans.sendMessage(msg, address);
                
            } catch (Exception mex) {
                mex.printStackTrace();
                
            } finally {
                try{
                    trans.close();
                }catch(MessagingException e){}
            }
    }

     // implement ConnectionListener interface
    public void opened(ConnectionEvent e) {
        System.out.println(">>> ConnectionListener.opened()");
    }
    public void disconnected(ConnectionEvent e) {}
    public void closed(ConnectionEvent e) {
        System.out.println(">>> ConnectionListener.closed()");
    }

    // implement TransportListener interface
    public void messageDelivered(TransportEvent e) {
        System.out.print(">>> TransportListener.messageDelivered().");
        System.out.println(" Valid Addresses:");
        Address[] valid = e.getValidSentAddresses();
        if (valid != null) {
            for (int i = 0; i < valid.length; i++) 
            System.out.println("    " + valid[i]);
        }
    }
    public void messageNotDelivered(TransportEvent e) {
        System.out.print(">>> TransportListener.messageNotDelivered().");
        System.out.println(" Invalid Addresses:");
        Address[] invalid = e.getInvalidAddresses();
        if (invalid != null) {
            for (int i = 0; i < invalid.length; i++) 
            System.out.println("    " + invalid[i]);
        }
    }
    public void messagePartiallyDelivered(TransportEvent e) {
    // SMTPTransport doesn't partially deliver msgs
    }
}

mbp2.setFileName(MimeUtility.encodeText(fds.getName(), "euc-kr","B")); // 헤더에 파일이름을 세팅할때 base64형태로 반드시 파일이름을 변환시켜준다.
 
1 2 3 4
References
 
아티클소스 : javaMail2.zip
Copyright ⓒ 2003 www.javapattern.info & www.jlook.com, an jLOOK co.,LTD