001: package org.claros.intouch.webmail.services;
002:
003: import java.io.BufferedInputStream;
004: import java.io.ByteArrayOutputStream;
005: import java.io.File;
006: import java.io.FileInputStream;
007: import java.io.IOException;
008: import java.io.ObjectOutputStream;
009: import java.io.PrintWriter;
010: import java.util.ArrayList;
011: import java.util.Date;
012: import java.util.HashMap;
013: import java.util.List;
014: import java.util.Locale;
015:
016: import javax.activation.DataHandler;
017: import javax.activation.DataSource;
018: import javax.mail.Address;
019: import javax.mail.internet.InternetAddress;
020: import javax.mail.internet.MimeBodyPart;
021: import javax.mail.internet.MimeMessage;
022: import javax.servlet.ServletException;
023: import javax.servlet.http.HttpServletRequest;
024: import javax.servlet.http.HttpServletResponse;
025:
026: import org.apache.commons.logging.Log;
027: import org.apache.commons.logging.LogFactory;
028: import org.claros.commons.auth.models.AuthProfile;
029: import org.claros.commons.cache.Cache;
030: import org.claros.commons.cache.CacheManager;
031: import org.claros.commons.configuration.Paths;
032: import org.claros.commons.configuration.PropertyFile;
033: import org.claros.commons.mail.models.ByteArrayDataSource;
034: import org.claros.commons.mail.models.ConnectionMetaHandler;
035: import org.claros.commons.mail.models.ConnectionProfile;
036: import org.claros.commons.mail.models.Email;
037: import org.claros.commons.mail.models.EmailHeader;
038: import org.claros.commons.mail.models.EmailPart;
039: import org.claros.commons.mail.protocols.Smtp;
040: import org.claros.commons.mail.utility.Utility;
041: import org.claros.commons.utility.MD5;
042: import org.claros.intouch.common.services.BaseService;
043: import org.claros.intouch.contacts.controllers.ContactsController;
044: import org.claros.intouch.preferences.controllers.UserPrefsController;
045: import org.claros.intouch.webmail.controllers.FolderController;
046: import org.claros.intouch.webmail.controllers.MailController;
047: import org.claros.intouch.webmail.factory.FolderControllerFactory;
048: import org.claros.intouch.webmail.factory.MailControllerFactory;
049: import org.claros.intouch.webmail.models.MsgDbObject;
050: import org.claros.intouch.webmail.models.FolderDbObject;
051:
052: public class SendMailService extends BaseService {
053:
054: /**
055: *
056: */
057: private static final long serialVersionUID = -7451365138227115574L;
058: private static Log log = LogFactory.getLog(SendMailService.class);
059:
060: /**
061: * The doPost method of the servlet. <br>
062: *
063: * This method is called when a form has its tag value method equals to post.
064: *
065: * @param request the request send by the client to the server
066: * @param response the response send by the server to the client
067: * @throws ServletException if an error occurred
068: * @throws IOException if an error occurred
069: */
070: public void doPost(HttpServletRequest request,
071: HttpServletResponse response) throws ServletException,
072: IOException {
073:
074: response.setHeader("Expires", "-1");
075: response.setHeader("Pragma", "no-cache");
076: response.setHeader("Cache-control", "no-cache");
077: response.setHeader("Content-Type", "text/html; charset=utf-8");
078:
079: PrintWriter out = response.getWriter();
080:
081: try {
082: String from = request.getParameter("from");
083: String to = request.getParameter("to");
084: String cc = request.getParameter("cc");
085: String bcc = request.getParameter("bcc");
086: String subject = request.getParameter("subject");
087: String body = request.getParameter("body");
088: String requestReceiptNotification = request
089: .getParameter("requestReceiptNotification");
090: String priority = request.getParameter("priority");
091: String sensitivity = request.getParameter("sensitivity");
092:
093: // learn the global charset setting.
094:
095: // learn user preferences from the DB.
096: AuthProfile auth = getAuthProfile(request);
097:
098: String saveSentContacts = UserPrefsController
099: .getUserSetting(auth, "saveSentContacts");
100: if (saveSentContacts == null) {
101: saveSentContacts = "yes";
102: }
103:
104: // now create a new email object.
105: Email email = new Email();
106: EmailHeader header = new EmailHeader();
107:
108: Address adrs[] = Utility.stringToAddressArray(from);
109: header.setFrom(adrs);
110:
111: Address tos[] = Utility.stringToAddressArray(to);
112: header.setTo(tos);
113: if (saveSentContacts != null
114: && saveSentContacts.equals("yes")) {
115: saveContacts(auth, tos);
116: }
117:
118: if (cc != null && cc.trim() != "") {
119: Address ccs[] = Utility.stringToAddressArray(cc);
120: header.setCc(ccs);
121: if (saveSentContacts != null
122: && saveSentContacts.equals("yes")) {
123: saveContacts(auth, ccs);
124: }
125: }
126: if (bcc != null && bcc.trim() != "") {
127: Address bccs[] = Utility.stringToAddressArray(bcc);
128: header.setBcc(bccs);
129: if (saveSentContacts != null
130: && saveSentContacts.equals("yes")) {
131: saveContacts(auth, bccs);
132: }
133: }
134: header.setSubject(subject);
135: header.setDate(new Date());
136:
137: String replyTo = UserPrefsController.getUserSetting(auth,
138: "replyTo");
139: if (replyTo != null && replyTo.trim().length() != 0) {
140: header.setReplyTo(new Address[] { new InternetAddress(
141: replyTo) });
142: }
143:
144: if (requestReceiptNotification != null
145: && requestReceiptNotification.equals("1")) {
146: header.setRequestReceiptNotification(Boolean
147: .valueOf(true));
148: }
149:
150: if (priority != null) {
151: header
152: .setPriority(Short.valueOf(priority)
153: .shortValue());
154: }
155:
156: if (sensitivity != null) {
157: header.setSensitivity(Short.valueOf(sensitivity)
158: .shortValue());
159: }
160:
161: email.setBaseHeader(header);
162:
163: ArrayList parts = new ArrayList();
164: EmailPart bodyPart = new EmailPart();
165: bodyPart.setContentType("text/html; charset=UTF-8");
166: /*
167: HtmlCleaner cleaner = new HtmlCleaner(body);
168: cleaner.clean(false,false);
169: */
170:
171: String appendSignature = PropertyFile.getConfiguration(
172: "/config/config.xml").getString(
173: "common-params.append-signature");
174: String sign = "";
175: if (appendSignature != null
176: && appendSignature.toLowerCase().equals("true")) {
177: Cache cache = CacheManager
178: .getContent("server.signature");
179: if (cache == null) {
180: BufferedInputStream is = new BufferedInputStream(
181: new FileInputStream(Paths.getCfgFolder()
182: + "/server_signature.txt"));
183: int byte_;
184: ByteArrayOutputStream bos = new ByteArrayOutputStream();
185: while ((byte_ = is.read()) != -1) {
186: bos.write(byte_);
187: }
188: is.close();
189: sign = new String(bos.toByteArray());
190: bos.close();
191:
192: cache = new Cache();
193: CacheManager.putContent("server.signature", sign,
194: Integer.MAX_VALUE);
195: } else {
196: sign = (String) cache.getValue();
197: }
198: }
199: body = body + sign;
200: bodyPart.setContent(body);
201: parts.add(0, bodyPart);
202:
203: // attach some files...
204: ArrayList attachments = (ArrayList) request.getSession()
205: .getAttribute("attachments");
206: if (attachments != null) {
207: List newLst = new ArrayList();
208: EmailPart tmp = null;
209: for (int i = 0; i < attachments.size(); i++) {
210: try {
211: tmp = (EmailPart) attachments.get(i);
212: String disp = tmp.getDisposition();
213: File f = new File(disp);
214: BufferedInputStream bis = new BufferedInputStream(
215: new FileInputStream(f));
216: byte data[] = new byte[(int) f.length() + 2];
217: bis.read(data);
218: bis.close();
219:
220: MimeBodyPart bp = new MimeBodyPart();
221: DataSource ds = new ByteArrayDataSource(data,
222: tmp.getContentType(), tmp.getFilename());
223: bp.setDataHandler(new DataHandler(ds));
224: bp.setDisposition("attachment; filename=\""
225: + tmp.getFilename() + "\"");
226: tmp.setDisposition(bp.getDisposition());
227: bp.setFileName(tmp.getFilename());
228: tmp.setDataSource(ds);
229: tmp.setContent(bp.getContent());
230: newLst.add(tmp);
231:
232: } catch (Exception e) {
233: e.printStackTrace();
234: }
235: }
236: parts.addAll(newLst);
237: }
238: email.setParts(parts);
239:
240: // it is time to send the email object message
241: Smtp smtp = new Smtp(getConnectionProfile(request),
242: getAuthProfile(request));
243: HashMap sendRes = smtp.send(email, false);
244: MimeMessage msg = (MimeMessage) sendRes.get("msg");
245:
246: // if we fail to send the message to any of the recepients
247: // we should make a report about it to the user.
248: Address[] sent = (Address[]) sendRes.get("sent");
249: // Address[] fail = (Address[])sendRes.get("fail");
250: // Address[] invalid = (Address[])sendRes.get("invalid");
251:
252: if (sent == null || sent.length == 0) {
253: out.print("fail");
254: } else {
255: // if save to sent items enabled, save the sent mail.
256: String saveEnabled = UserPrefsController
257: .getUserSetting(auth, "saveSent");
258: if (saveEnabled == null) {
259: saveEnabled = "yes";
260: }
261: if (saveEnabled == null || saveEnabled.equals("yes")) {
262: saveSentMail(auth, msg, request);
263: }
264: out.print("ok");
265: }
266: } catch (Exception e) {
267: out.print("fail");
268: }
269: }
270:
271: /**
272: *
273: * @param auth
274: * @param adrs
275: */
276: private void saveContacts(AuthProfile auth, Address[] adrs) {
277: try {
278: if (adrs != null) {
279: InternetAddress adr = null;
280: for (int i = 0; i < adrs.length; i++) {
281: adr = (InternetAddress) adrs[i];
282: ContactsController.saveSenderFromAddr(auth, adr);
283: }
284: }
285: } catch (Exception e) {
286: log.debug("save contact failed.", e);
287: }
288:
289: }
290:
291: /**
292: *
293: * @param auth
294: * @param msg
295: * @param request
296: * @throws Exception
297: */
298: private void saveSentMail(AuthProfile auth, MimeMessage msg,
299: HttpServletRequest request) throws Exception {
300: ByteArrayOutputStream bos = new ByteArrayOutputStream();
301: msg.writeTo(bos);
302: byte bMsg[] = bos.toByteArray();
303:
304: // serialize the message byte array
305: ObjectOutputStream os = new ObjectOutputStream(bos);
306: os.writeObject(bMsg);
307:
308: // create an email db item
309: MsgDbObject item = new MsgDbObject();
310: item.setEmail(bMsg);
311: String md5Header = new String(MD5.getHashString(bMsg))
312: .toUpperCase(new Locale("en", "US"));
313:
314: ConnectionMetaHandler handler = getConnectionHandler(request);
315: ConnectionProfile profile = getConnectionProfile(request);
316:
317: FolderControllerFactory factory = new FolderControllerFactory(
318: auth, profile, handler);
319: FolderController foldCont = factory.getFolderController();
320: FolderDbObject fItem = foldCont.getSentItems();
321:
322: item.setUniqueId(md5Header);
323: item.setFolderId(fItem.getId());
324: item.setUnread(new Boolean(false));
325: item.setUsername(auth.getUsername());
326: item.setMsgSize(new Long(bMsg.length));
327:
328: // save the email db item.
329: MailControllerFactory mailFact = new MailControllerFactory(
330: auth, profile, handler, fItem.getFolderName());
331: MailController mailCont = mailFact.getMailController();
332: mailCont.appendEmail(item);
333: }
334: }
|