001: /**
002: * $Id: SendFile.java,v 1.13 2005/11/30 11:26:40 ss150821 Exp $
003: * Copyright 2002 Sun Microsystems, Inc. All
004: * rights reserved. Use of this product is subject
005: * to license terms. Federal Acquisitions:
006: * Commercial Software -- Government Users
007: * Subject to Standard License Terms and
008: * Conditions.
009: *
010: * Sun, Sun Microsystems, the Sun logo, and Sun ONE
011: * are trademarks or registered trademarks of Sun Microsystems,
012: * Inc. in the United States and other countries.
013: */package com.sun.portal.netfile.servlet.java2;
014:
015: import java.util.*;
016: import com.sun.portal.log.common.PortalLogger;
017: import java.util.logging.*;
018: import java.io.*;
019: import javax.mail.*;
020: import javax.mail.Session;
021: import javax.mail.internet.*;
022: import javax.activation.*;
023: import java.net.UnknownHostException;
024: import java.io.UnsupportedEncodingException;
025:
026: import com.sun.portal.netfile.shared.*;
027:
028: /**
029: * SendFile will create a multipart message with the second
030: * block of the message being the given file.<p>
031: *
032: * this demonstrates how to use the FileDataSource to send
033: * a file via mail.<p>
034: *
035: * usage: <code>java SendFile <i>to from smtp file true|false</i></code>
036: * where <i>to</i> and <i>from</i> are the destination and
037: * origin email addresses, respectively, and <i>smtp</i>
038: * is the hostname of the machine that has smtp server
039: * running. The file is the file to send. the message next parameter either turns on or turns off
040: * debugging during sending.
041: *
042: * @version 1.4, 98/06/16
043: * @author Christopher Cotton
044: * @modified by Suresh Yellamaraju and Ali Baqri
045: */
046:
047: class SendFile {
048:
049: private static Logger logger = PortalLogger
050: .getLogger(SendFile.class);
051:
052: SendFile() {
053: }
054:
055: String encode(String s_to_be_encoded, String character_set)
056: throws Exception {
057: if (character_set == null) {
058: } else if (character_set.equals("")) {
059: } else {
060: s_to_be_encoded = MimeUtility.encodeText(s_to_be_encoded,
061: character_set, "B");
062: }
063: return s_to_be_encoded;
064: }
065:
066: String sendAttachedFile(String to, String from, String replyto,
067: String cc, String bcc, String host, String subject,
068: String message, Map filetosendList, String dbgval,
069: String charSet,
070: NetFileResource nfr_user_locale_i18n_bucket,
071: String displayFileName) throws NetFileException {
072: boolean toAddressException = false; // check whether AddressException is thrown when parsing TO address.
073: boolean ccAddressException = false;
074: boolean bccAddressException = false;
075:
076: try {
077: // logger.info("Charset="+charSet);
078: Object[] params0 = { charSet };
079: logger.log(Level.INFO, "PSSRNF_CSPNSJ2119", params0);
080: if (charSet.equals("")) {
081: charSet = "UTF8";
082: }
083: // convert java charset into its MIME charset name
084: charSet = MimeUtility.mimeCharset(charSet);
085:
086: boolean debug = Boolean.valueOf(dbgval).booleanValue();
087: InternetAddress[] toaddress = null, ccaddress = null, bccaddress = null;
088: // create some properties and get the default Session
089: Properties props = System.getProperties();
090: props.put("mail.smtp.host", host);
091:
092: Session session = Session.getDefaultInstance(props, null);
093: session.setDebug(debug);
094: if (!charSet.equals("")) {
095: String firstFrom = "";
096: String restFrom = "";
097: int leftAnglendx;
098: leftAnglendx = from.indexOf("<");
099: if (leftAnglendx >= 0) {
100: firstFrom = from.substring(0, leftAnglendx);
101: restFrom = from.substring(leftAnglendx);
102: //firstFrom = MimeUtility.encodeText(firstFrom, charset, null);
103: firstFrom = encode(firstFrom, charSet);
104: from = firstFrom + restFrom;
105: }
106:
107: String firstTo = "";
108: String restTo = "";
109: leftAnglendx = to.indexOf("<");
110: if (leftAnglendx >= 0) {
111: firstTo = to.substring(0, leftAnglendx);
112: restTo = to.substring(leftAnglendx);
113: //firstTo = MimeUtility.encodeText(firstTo, charset, null);
114: firstTo = encode(firstTo, charSet);
115: to = firstTo + restTo;
116: }
117:
118: String firstReply = "";
119: String restReply = "";
120: leftAnglendx = replyto.indexOf("<");
121: if (leftAnglendx >= 0) {
122: firstReply = replyto.substring(0, leftAnglendx);
123: restReply = replyto.substring(leftAnglendx);
124: //firstReply = MimeUtility.encodeText(firstReply, charSet, null);
125: firstReply = encode(firstReply, charSet);
126: replyto = firstReply + restReply;
127: }
128:
129: String firstCC = "";
130: String restCC = "";
131: leftAnglendx = cc.indexOf("<");
132: if (leftAnglendx >= 0) {
133: firstCC = cc.substring(0, leftAnglendx);
134: restCC = cc.substring(leftAnglendx);
135: //firstCC = MimeUtility.encodeText(firstCC, charSet, null);
136: firstCC = encode(firstCC, charSet);
137: cc = firstCC + restCC;
138: }
139:
140: String firstBCC = "";
141: String restBCC = "";
142: leftAnglendx = bcc.indexOf("<");
143: if (leftAnglendx >= 0) {
144: firstBCC = bcc.substring(0, leftAnglendx);
145: restBCC = bcc.substring(leftAnglendx);
146: //firstBCC = MimeUtility.encodeText(firstBCC, charSet, null);
147: firstBCC = encode(firstBCC, charSet);
148: bcc = firstBCC + restBCC;
149: }
150: }
151: // create a message
152: MimeMessage msg = new MimeMessage(session);
153: //msg.setHeader("Content-Type","text/plain; charset="+charSet);
154: //msg.setHeader("Content-Transfer-Encoding","base64");
155: msg.setFrom(new InternetAddress(from));
156:
157: try {
158: toaddress = this .parseAddress(to);
159: msg.setRecipients(Message.RecipientType.TO, toaddress);
160: } catch (AddressException ae) {
161: toAddressException = true;
162: // logger.log(Level.SEVERE, "AddressException while parsing TO address, ", ae);
163: logger.log(Level.SEVERE, "PSSRNF_CSPNSJ2120");
164: }
165:
166: if ((replyto == null) || (replyto.equals(""))) {
167: replyto = from;
168: }
169: InternetAddress[] replytoaddress = { new InternetAddress(
170: replyto) };
171: msg.setReplyTo(replytoaddress);
172:
173: if (cc.equals("") || (cc == null)) {
174: } else {
175: try {
176: ccaddress = this .parseAddress(cc);
177: msg.setRecipients(Message.RecipientType.CC,
178: ccaddress);
179: } catch (AddressException ae) {
180: ccAddressException = true;
181: // logger.log(Level.SEVERE, "AddressException while parsing CC address, ", ae);
182: logger.log(Level.SEVERE, "PSSRNF_CSPNSJ2121");
183:
184: }
185: }
186:
187: if (bcc.equals("") || (bcc == null)) {
188: } else {
189: try {
190: bccaddress = this .parseAddress(bcc);
191: msg.setRecipients(Message.RecipientType.BCC,
192: bccaddress);
193: } catch (AddressException ae) {
194: bccAddressException = true;
195: // logger.log(Level.SEVERE, "AddressException while parsing BCC address, ", ae);
196: logger.log(Level.SEVERE, "PSSRNF_CSPNSJ2122");
197: }
198: }
199:
200: msg.setSubject(encode(subject, charSet));
201: // create and fill the first message part
202: MimeBodyPart mbp1 = new MimeBodyPart();
203: mbp1.setText(message, charSet);
204:
205: Multipart mp = new MimeMultipart();
206: mp.addBodyPart(mbp1);
207:
208: Iterator it = filetosendList.keySet().iterator();
209: while (it.hasNext()) {
210: Object theFileName = it.next();
211: String thefile = (filetosendList.get(theFileName))
212: .toString();
213:
214: // create the second message part
215: MimeBodyPart mbp2 = new MimeBodyPart();
216:
217: // attach the file to the message
218: FileDataSource fds = new FileDataSource(theFileName
219: .toString());
220: mbp2.setDataHandler(new DataHandler(fds));
221:
222: mbp2.setFileName(encode(thefile, charSet));
223: mbp2.setHeader("Content-Type",
224: "application/octet-stream; charset=" + charSet);
225: mbp2.setHeader("Content-Transfer-Encoding", "base64");
226:
227: mp.addBodyPart(mbp2);
228: }
229:
230: // add the Multipart to the message
231: msg.setContent(mp);
232:
233: // set the Date: header
234: msg.setSentDate(new Date());
235:
236: // send the message
237: Transport.send(msg);
238: } catch (Exception e) {
239: processException(e, host, nfr_user_locale_i18n_bucket);
240: }
241: // logger.info("Did not throw exception properly");
242: logger.info("PSSRNF_CSPNSJ2123");
243: //Check whether there was any Address Exception while parsing To,Cc,Bcc address.
244: String displayAddress = "";
245: if (toAddressException) {
246: displayAddress += "To: " + to + "\n";
247: }
248: if (ccAddressException) {
249: displayAddress += "Cc: " + cc + "\n";
250: }
251: if (bccAddressException) {
252: displayAddress += "Bcc: " + bcc + "\n";
253: }
254: if (!displayAddress.equals("")) {
255: return nfr_user_locale_i18n_bucket.getString("sfErr.7")
256: + displayAddress;
257: // sfErr.7 - Mail has not been sent to one/more recepients:
258: } else {
259: return nfr_user_locale_i18n_bucket.getString("info8");
260: }
261: }
262:
263: private void processException(Exception e, String host,
264: NetFileResource nfRes) throws NetFileException {
265: // logger.log(Level.SEVERE, "Exception is sending the message",e);
266: logger.log(Level.SEVERE, "PSSRNF_CSPNSJ2124");
267: if (e instanceof MessagingException) {
268: MessagingException me = (MessagingException) e;
269: while (true) {
270: Exception mex = me.getNextException();
271: if (mex != null) {
272: if (mex instanceof MessagingException) {
273: me = (MessagingException) mex;
274: } else if (mex instanceof UnknownHostException) {
275: throw new NetFileException(
276: NetFileException.NETFILE_UNKNOWN_HOST_EXCEPTION,
277: nfRes.getString("sfErr.4")); // sfErr.4 - Mail not sent. Mail Server unknown.
278: } else if (mex instanceof AuthenticationFailedException) {
279: throw new NetFileException(
280: NetFileException.NETFILE_AUTHENTICATION_FAILED_EXCEPTION,
281: nfRes.getString("sfErr.5")); // sfErr.5 - Mail not sent. Authentication failed.
282: } else if (mex instanceof SendFailedException) {
283: throw new NetFileException(
284: NetFileException.NETFILE_SEND_FAILED_EXCEPTION,
285: nfRes.getString("sfErr.8")); // sfErr.8 - Mail not sent.
286: }
287: } else {
288: break;
289: }
290: }
291: //throw new NetFileException(new String[]{host,NetFileException.KEY_IDENTIFIER_PREFIX+"textseperator",
292: //NetFileException.KEY_IDENTIFIER_PREFIX+"mail_not_sent"});
293: throw new NetFileException(
294: NetFileException.NETFILE_SEND_FAILED_EXCEPTION,
295: nfRes.getString("sfErr.8"));
296: } else if (e instanceof UnsupportedEncodingException) {
297: throw new NetFileException(
298: NetFileException.NETFILE_UNSUPPORTED_ENCODING_EXCEPTION,
299: nfRes.getString("sfErr.6")); // sfErr.6 - Mail not sent. Unsuppoted Encoding.
300: } else {
301: // logger.info("Throwing generic exception");
302: logger.info("PSSRNF_CSPNSJ2125");
303: throw new NetFileException(
304: NetFileException.NETFILE_SEND_FAILED_EXCEPTION,
305: nfRes.getString("sfErr.8"));
306: }
307: }
308:
309: /*
310: * Parse s into an array of InternetAddresses that are properly encoded
311: * based on the charset encoding.
312: */
313:
314: InternetAddress[] parseAddress(String s, String charset)
315: throws AddressException {
316: InternetAddress[] addrs = InternetAddress.parse(s);
317:
318: if (charset != null) {
319: for (int i = 0; i < addrs.length; i++) {
320: String personal = addrs[i].getPersonal();
321: if (personal != null) {
322: try {
323: //personal = MimeUtility.encodeText(personal, charset, null);
324: personal = encode(personal, charset);
325: addrs[i].setPersonal(personal);
326: } catch (Exception e) {
327: }
328: }
329: }
330: }
331: return addrs;
332: }
333:
334: /**
335: * Bug 4494943
336: * Created to parse the string for comma delimited internet mail addresses
337: * The use of personal names is not allowed and no effort is being made
338: * as part of this function to parse for personal names and seperate them from
339: * the internet email addresses.
340: *
341: * Thus email are expected to be entered by the user of two forms
342: * 1. internetEmailAddress@domain
343: * 2. emailAddress
344: * Both forms should have commas seperators.
345: *
346: * This function has been created as the InternetAddress.parse(String) function
347: * is throwing AddressException for valid email addresses.
348: *
349: */
350: InternetAddress[] parseAddress(String s) throws AddressException {
351: javax.mail.internet.InternetAddress[] addrs = null;
352: javax.mail.internet.InternetAddress addr = null;
353: ArrayList addrsList = new ArrayList();
354:
355: java.util.StringTokenizer parsedAddrs = new java.util.StringTokenizer(
356: s, ",");
357:
358: while (parsedAddrs.hasMoreTokens()) {
359: addr = new javax.mail.internet.InternetAddress(parsedAddrs
360: .nextToken());
361: addrsList.add(addr);
362: }
363:
364: addrs = new InternetAddress[addrsList.size()];
365: addrsList.toArray(addrs);
366: return addrs;
367: }
368:
369: }
|