SendMessage.java
上传用户:huihesys
上传日期:2007-01-04
资源大小:3877k
文件大小:10k
- /* CVS ID: $Id: SendMessage.java,v 1.3 2000/04/06 08:02:02 wastl Exp $ */
- import net.wastl.webmail.server.*;
- import net.wastl.webmail.server.http.*;
- import net.wastl.webmail.ui.html.*;
- import net.wastl.webmail.ui.xml.*;
- import net.wastl.webmail.misc.*;
- import net.wastl.webmail.config.ConfigurationListener;
- import java.io.*;
- import java.util.*;
- import java.text.*;
- import javax.mail.*;
- import javax.mail.internet.*;
- /*
- * SendMessage.java
- *
- * Created: Tue Sep 7 13:59:30 1999
- *
- * Copyright (C) 1999-2000 Sebastian Schaffert
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
- */
- /**
- * Send a message and show a result page.
- *
- * provides: message send
- * requires: composer
- *
- * @author Sebastian Schaffert
- * @version
- */
- public class SendMessage implements Plugin, URLHandler, ConfigurationListener {
-
- public static final String VERSION="1.5";
- public static final String URL="/send";
-
- Storage store;
- WebMailServer parent;
- Session mailsession;
- public SendMessage() {
-
- }
- public void register(WebMailServer parent) {
- parent.getURLHandler().registerHandler(URL,this);
- parent.getConfigScheme().configRegisterStringKey(this,"SMTP HOST","localhost","Host used to send messages via SMTP. Should be localhost or your SMTP smarthost");
- this.store=parent.getStorage();
- this.parent=parent;
- }
- protected void init() {
- Properties props=new Properties();
- props.put("mail.host",store.getConfig("SMTP HOST"));
- props.put("mail.smtp.host",store.getConfig("SMTP HOST"));
- mailsession=Session.getDefaultInstance(props,null);
- }
- public String getName() {
- return "SendMessage";
- }
- public String getDescription() {
- return "This URL-Handler sends a submitted message.";
- }
- public String getVersion() {
- return VERSION;
- }
- public String getURL() {
- return URL;
- }
-
- public void notifyConfigurationChange(String key) {
- init();
- }
- public HTMLDocument handleURL(String suburl, HTTPSession sess1, HTTPRequestHeader head) throws WebMailException {
- if(sess1 == null) {
- throw new WebMailException("No session was given. If you feel this is incorrect, please contact your system administrator");
- }
- WebMailSession session=(WebMailSession)sess1;
- UserData user=session.getUser();
- HTMLDocument content;
- /* Save message in case there is an error */
- session.storeMessage(head);
- if(head.isContentSet("SEND")) {
- /* The form was submitted, now we will send it ... */
- try {
- MimeMessage msg=new MimeMessage(mailsession);
- Address from[]=new Address[1];
- try {
- from[0]=new InternetAddress(MimeUtility.encodeText(session.getUser().getEmail()),
- MimeUtility.encodeText(session.getUser().getFullName()));
- } catch(UnsupportedEncodingException e) {
- store.log(Storage.LOG_WARN,"Unsupported Encoding while trying to send message: "+e.getMessage());
- from[0]=new InternetAddress(session.getUser().getEmail(),session.getUser().getFullName());
- }
-
- StringTokenizer t;
- try {
- t=new StringTokenizer(MimeUtility.encodeText(head.getContent("TO")).trim(),",");
- } catch(UnsupportedEncodingException e) {
- store.log(Storage.LOG_WARN,"Unsupported Encoding while trying to send message: "+e.getMessage());
- t=new StringTokenizer(head.getContent("TO").trim(),",;");
- }
- /* Check To: field, when empty, throw an exception */
- if(t.countTokens()<1) {
- throw new MessagingException("The recipient field must not be empty!");
- }
- Address to[]=new Address[t.countTokens()];
- int i=0;
- while(t.hasMoreTokens()) {
- to[i]=new InternetAddress(t.nextToken().trim());
- i++;
- }
-
- try {
- t=new StringTokenizer(MimeUtility.encodeText(head.getContent("CC")).trim(),",");
- } catch(UnsupportedEncodingException e) {
- store.log(Storage.LOG_WARN,"Unsupported Encoding while trying to send message: "+e.getMessage());
- t=new StringTokenizer(head.getContent("CC").trim(),",;");
- }
- Address cc[]=new Address[t.countTokens()];
- i=0;
- while(t.hasMoreTokens()) {
- cc[i]=new InternetAddress(t.nextToken().trim());
- i++;
- }
-
- try {
- t=new StringTokenizer(MimeUtility.encodeText(head.getContent("BCC")).trim(),",");
- } catch(UnsupportedEncodingException e) {
- store.log(Storage.LOG_WARN,"Unsupported Encoding while trying to send message: "+e.getMessage());
- t=new StringTokenizer(head.getContent("BCC").trim(),",;");
- }
- Address bcc[]=new Address[t.countTokens()];
- i=0;
- while(t.hasMoreTokens()) {
- bcc[i]=new InternetAddress(t.nextToken().trim());
- i++;
- }
-
- session.setSent(false);
- msg.addFrom(from);
- if(to.length > 0) {
- msg.addRecipients(Message.RecipientType.TO,to);
- }
- if(cc.length > 0) {
- msg.addRecipients(Message.RecipientType.CC,cc);
- }
- if(bcc.length > 0) {
- msg.addRecipients(Message.RecipientType.BCC,bcc);
- }
- msg.addHeader("X-Mailer",WebMailServer.getVersion()+", "+getName()+" plugin v"+getVersion());
- String subject;
- if(head.getContent("SUBJECT") == null || head.getContent("SUBJECT").equals("")) {
- subject="no subject";
- } else {
- try {
- subject=MimeUtility.encodeText(head.getContent("SUBJECT"));
- } catch(UnsupportedEncodingException e) {
- store.log(Storage.LOG_WARN,"Unsupported Encoding while trying to send message: "+e.getMessage());
- subject=head.getContent("SUBJECT");
- }
- }
-
- msg.addHeader("Subject",subject);
- msg.addHeader("Reply-To",head.getContent("REPLY-TO"));
-
- msg.setSentDate(new Date(System.currentTimeMillis()));
-
- String contnt=head.getContent("BODY");
- String charset=MimeUtility.mimeCharset(MimeUtility.getDefaultJavaCharset());
- MimeMultipart cont=new MimeMultipart();
- MimeBodyPart txt=new MimeBodyPart();
- try {
- txt.setText(MimeUtility.encodeText(contnt,charset,"base64"));
- } catch(UnsupportedEncodingException e) {
- store.log(Storage.LOG_WARN,"Unsupported Encoding while trying to send message: "+e.getMessage());
- txt.setText(contnt);
- }
- cont.addBodyPart(txt);
- Enumeration atts=session.getAttachments().keys();
- while(atts.hasMoreElements()) {
- ByteStore bs=session.getAttachment((String)atts.nextElement());
- InternetHeaders ih=new InternetHeaders();
- ih.addHeader("Content-Type",bs.getContentType());
- ih.addHeader("Content-Transfer-Encoding","BASE64");
- InputStream decoded=(ByteArrayInputStream)MimeUtility.decode(new ByteArrayInputStream(bs.getBytes()),bs.getContentEncoding());
- ByteStore bs2=ByteStore.getBinaryFromIS(decoded,decoded.available()+1000);
-
- PipedInputStream pin=new PipedInputStream();
- PipedOutputStream pout=new PipedOutputStream(pin);
-
- /* This is used to write to the Pipe asynchronously to avoid blocking */
- StreamConnector sconn=new StreamConnector(pin,(int)(bs2.getSize()*1.6)+1000);
- BufferedOutputStream encoder=new BufferedOutputStream(MimeUtility.encode(pout,"BASE64"));
- encoder.write(bs.getBytes());
- encoder.flush();
- encoder.close();
- //MimeBodyPart att1=sconn.getResult();
- MimeBodyPart att1=new MimeBodyPart(ih,sconn.getResult().getBytes());
-
-
- att1.addHeader("Content-Type",bs.getContentType());
- att1.setDescription(bs.getDescription());
- att1.setFileName(bs.getName());
- cont.addBodyPart(att1);
- }
- msg.setContent(cont);
- // }
-
- msg.saveChanges();
- boolean savesuccess=true;
- msg.setHeader("Message-ID",session.getUserModel().getWorkMessage().getAttribute("msgid"));
- if(session.getUser().wantsSaveSent()) {
- String folderhash=session.getUser().getSentFolder();
- try {
- Folder folder=session.getFolder(folderhash);
- Message[] m=new Message[1];
- m[0]=msg;
- folder.appendMessages(m);
- } catch(MessagingException e) {
- savesuccess=false;
- } catch(NullPointerException e) {
- // Invalid folder:
- savesuccess=false;
- }
- }
- boolean sendsuccess=false;
- try {
- Transport.send(msg);
- Address sent[]=new Address[to.length+cc.length+bcc.length];
- int c1=0;int c2=0;
- for(c1=0;c1<to.length;c1++) {
- sent[c1]=to[c1];
- }
- for(c2=0;c2<cc.length;c2++) {
- sent[c1+c2]=cc[c2];
- }
- for(int c3=0;c3<bcc.length;c3++) {
- sent[c1+c2+c3]=bcc[c3];
- }
- sendsuccess=true;
- throw new SendFailedException("success",new Exception("success"),sent,null,null);
- } catch(SendFailedException e) {
- session.handleTransportException(e);
- }
-
- //session.clearMessage();
- //content=new HTMLParsedDocument(store,session,"send result");
- content=new XHTMLDocument(session.getModel(),
- store.getStylesheet("sendresult.xsl",
- user.getPreferredLocale(),user.getTheme()));
- if(sendsuccess) session.clearWork();
- } catch(Exception e) {
- e.printStackTrace();
- throw new DocumentNotFoundException("Could not send message. (Reason: "+e.getMessage()+")");
- }
-
- } else if(head.isContentSet("ATTACH")) {
- /* Redirect request for attachment (unfortunately HTML forms are not flexible enough to
- have two targets without Javascript) */
- content=parent.getURLHandler().handleURL("/compose/attach",session,head);
- } else {
- throw new DocumentNotFoundException("Could not send message. (Reason: No content given)");
- }
- return content;
- }
- public String provides() {
- return "message send";
- }
- public String requires() {
- return "composer";
- }
- } // SendMessage