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