View Javadoc

1   package org.opensync.tools;
2   
3   import java.io.*;
4   import java.net.*;
5   import java.util.*;
6   import javax.activation.*;
7   import javax.mail.*;
8   import javax.mail.internet.*;
9   
10  import org.xml.sax.*;
11  import org.xml.sax.helpers.*;
12  
13  import javax.xml.parsers.*;
14  
15  public class JMail extends DefaultHandler {
16  
17    private  Session session;
18    private Transport transport;
19    private String transportProtocol;
20    private String hostname;
21    private String username;
22    private String password;
23    private Vector recipients;
24    private Message message;
25    private Multipart multipart;
26    private Vector fromAddresses;
27    private Vector toAddresses;
28    private Vector ccAddresses;
29    private Vector bccAddresses;
30  
31    public JMail() {
32    }
33  
34    public Message getMessage() {
35      return message;
36    }
37  
38    public void startElement(String uri, String sName, String qName, Attributes atts) throws SAXException {
39  
40      try {
41        BodyPart bodyPart;
42  
43        String eName = sName; // element name
44        if ("".equals(eName)) eName = qName;
45  
46        if (eName.equals("connection")) {
47          if (atts != null) {
48            transportProtocol = atts.getValue("protocol");
49            hostname = atts.getValue("hostname");
50            username = atts.getValue("username");
51            password = atts.getValue("password");
52          }
53        }
54        if (eName.equals("message")) {
55          init(transportProtocol, hostname);
56          message = new MimeMessage(session);
57  	fromAddresses = new Vector();
58  	toAddresses = new Vector();
59  	ccAddresses = new Vector();
60  	bccAddresses = new Vector();
61        }
62  
63        if (eName.equals("recipient")) {
64          if (atts != null) {
65            if (atts.getValue("type").trim().toUpperCase().equals("FROM")) {
66  	    fromAddresses.add(new InternetAddress(atts.getValue("address")));
67            }
68            if (atts.getValue("type").trim().toUpperCase().equals("TO")) {
69  	    toAddresses.add(new InternetAddress(atts.getValue("address")));
70            }
71            if (atts.getValue("type").trim().toUpperCase().equals("CC")) {
72              ccAddresses.add(new InternetAddress(atts.getValue("address")));
73            }
74            if (atts.getValue("type").trim().toUpperCase().equals("BCC")) {
75              bccAddresses.add(new InternetAddress(atts.getValue("address")));
76            }
77          }
78        }
79        if (eName.equals("subject")) {
80          if (atts != null) {
81            message.setSubject(atts.getValue("text"));
82          }
83        }
84        if (eName.equals("body")) {
85          multipart = new MimeMultipart();
86        }
87  
88        if (eName.equals("part")) {
89          if (atts != null) {
90            bodyPart = new MimeBodyPart();
91            if (atts.getValue("type").equals("text")) {
92              bodyPart.setText(atts.getValue("value")+"\r\n");
93            }
94            if (atts.getValue("type").equals("file")) {
95              FileDataSource fileDataSource = new FileDataSource(atts.getValue("value"));
96              bodyPart.setDataHandler(new DataHandler(fileDataSource));
97              bodyPart.setFileName(fileDataSource.getName());
98            }
99            multipart.addBodyPart(bodyPart);
100         }
101       }
102     } catch (AddressException ae) {
103         throw new SAXException(ae);
104     }
105     catch(MessagingException me) {
106       throw new SAXException(me);
107     }
108   }
109 
110   public void endElement(String uri, String sName, String qName) throws SAXException {
111 
112     try {
113       String eName = sName; // element name
114       if ("".equals(eName)) eName = qName;
115 
116       if (eName.equals("body")) {
117             message.setContent(multipart);
118       }
119       if (eName.equals("message")) {
120 	Address[] addressesFROM = new Address[fromAddresses.size()];
121 	fromAddresses.toArray(addressesFROM);
122 	message.addFrom(addressesFROM);
123 	Address[] addressesTO = new Address[toAddresses.size()];
124 	toAddresses.toArray(addressesTO);
125 	message.addRecipients(Message.RecipientType.TO, addressesTO);
126 	Address[] addressesCC = new Address[ccAddresses.size()];
127 	ccAddresses.toArray(addressesCC);
128 	message.addRecipients(Message.RecipientType.CC, addressesCC);
129 	Address[] addressesBCC = new Address[bccAddresses.size()];
130 	bccAddresses.toArray(addressesBCC);
131 	message.addRecipients(Message.RecipientType.BCC, addressesBCC);
132 	message.saveChanges();
133       }
134       if (eName.equals("email")) {
135             //connect(hostname, username, password);
136       }
137     } catch(MessagingException me) {
138       throw new SAXException(me);
139     }
140   }
141 
142   public JMail(String xmlFileName) throws SAXException, ParserConfigurationException, MalformedURLException, IOException {
143 
144     SAXParserFactory factory = SAXParserFactory.newInstance();
145     factory.setValidating(true);
146     SAXParser parser = factory.newSAXParser();
147     parser.parse( new InputSource(new File(xmlFileName).toURL().toExternalForm()), this);
148   }
149 
150   // Receive notification of a recoverable error.
151   public void error(SAXParseException exception) throws SAXException {
152     String mesg_ex = "\r\nError at line "+exception.getLineNumber()+" in the file "+exception.getSystemId()+": "+exception.getLocalizedMessage();
153     throw new SAXException(mesg_ex);
154   }
155 
156   // Receive notification of a non-recoverable error.
157   public void fatalError(SAXParseException exception) throws SAXException {
158     String mesg_ex = "\r\nError at line "+exception.getLineNumber()+" in the file "+exception.getSystemId()+": "+exception.getLocalizedMessage();
159     throw new SAXException(mesg_ex);
160   }
161 
162   public void warning(SAXParseException exception) throws SAXException {
163     String mesg_ex = "\r\nError at line "+exception.getLineNumber()+" in the file "+exception.getSystemId()+": "+exception.getLocalizedMessage();
164     throw new SAXException(mesg_ex);
165   }
166 
167   public void init(String transport, String host) {
168 
169     transportProtocol = transport;
170     Properties properties = System.getProperties();
171     properties.put("mail.transport.protocol", transport);
172     properties.put("mail."+transport+".host", host);
173     session = Session.getInstance(properties,  null);
174   }
175 
176   public void addPart(String type, String part) throws IOException, MessagingException {
177     MimeMultipart multipart = (MimeMultipart)(((MimeMessage)this.getMessage()).getContent());
178     if (multipart == null)
179       multipart = new MimeMultipart();
180     BodyPart bodyPart = new MimeBodyPart();
181     if (type.equals("text")) {
182       bodyPart.setText(part);
183     }
184     if (type.equals("file")) {
185       FileDataSource fileDataSource = new FileDataSource(part);
186       bodyPart.setDataHandler(new DataHandler(fileDataSource));
187       bodyPart.setFileName(fileDataSource.getName());
188     }
189     multipart.addBodyPart(bodyPart);
190 
191     this.getMessage().setContent(multipart);
192     this.getMessage().saveChanges();
193   }
194 
195   public MimeMessage prepareMessage(String FromAddress, String toAddress, String subject, String text, String fileName) throws MessagingException {
196 
197     MimeMessage message = new MimeMessage(session);
198 
199     message.setFrom(new InternetAddress(FromAddress));
200     message.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
201     message.setSubject(subject);
202 
203     // Text part
204     BodyPart bodyPart1 = new MimeBodyPart();
205     bodyPart1.setText(text+"\r\n");
206 
207     // File part
208     BodyPart bodyPart2 = new MimeBodyPart();
209     FileDataSource fileDataSource = new FileDataSource(fileName);
210     bodyPart2.setDataHandler(new DataHandler(fileDataSource));
211     bodyPart2.setFileName(fileDataSource.getName());
212 
213     Multipart multipart = new MimeMultipart();
214     multipart.addBodyPart(bodyPart1);
215     multipart.addBodyPart(bodyPart2);
216 
217     message.setContent(multipart);
218     message.saveChanges();
219 
220     return message;
221   }
222 
223   public void connect(String host, String userName, String passWord) throws MessagingException {
224       transport = session.getTransport(transportProtocol);
225       transport.connect(host, userName, passWord);
226   }
227 
228   public void connect() throws MessagingException {
229       transport = session.getTransport(transportProtocol);
230       transport.connect(hostname, username, password);
231   }
232 
233   public void sendMessage() throws MessagingException, IOException {
234       transport.sendMessage(message, message.getAllRecipients());
235   }
236 
237   public void sendMessage(MimeMessage message) throws MessagingException {
238       transport.sendMessage(message, message.getAllRecipients());
239   }
240 
241   public void close() throws MessagingException {
242       transport.close();
243   }
244 }