Source Code Cross Referenced for SendMailService.java in  » Web-Mail » claros-intouch2-2.2-beta » org » claros » intouch » webmail » services » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Web Mail » claros intouch2 2.2 beta » org.claros.intouch.webmail.services 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


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:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.