Web Creation - еженедельный сетевой журнал для вебмастеров

   
 Посылка почты из Java. Часть 2:Java Mail

(c) General

В предедущей статье я привел класс который отсылает почту через sendmail, в это части - класс аналогичный по методам, но отсылающий почту при помощи JavaMail. Напомню что для работы, необходим не только Java Mail но и Activation Framework.

import java.io.*;
import java.net.*;
import java.util.*;

import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;

/**
 * Object wich allow sending html mail. Need sendmail
 * (this object is ported some my perl script).
 * @author Slava Komenda
 */
public class SendMail
{ protected String mailhost;
  protected InternetAddress from;

  protected String to;
  protected String msgbody;
  protected String subj;
  protected int msgType=1;

  public static int MESSAGE_TYPE_TEXT_PLAIN=0;
  public static int MESSAGE_TYPE_TEXT_HTML=1;
  
  public SendMail(String mailhost)
  { this.mailhost=mailhost;
  }

  public void setFrom(String From)
  { try { this.from=new InternetAddress(From);
        } catch (Exception e) {};
  }

  public void setMessageType(int msgType)
  { this.msgType=msgType;
  }

  public void setTo(String To)
  { to=To;
  }
    
  public void setSubj(String Subj)
  { subj=Subj;
  }

  public void setMessageBody(String MessageBody)
  { msgbody=MessageBody;
  }
/**
  * Sends e-mail to one recepient
  */
  final public boolean send()
// msgType: 0 - send mail as plain/text,
// other - send mail as html/text
  { boolean res=true;
    try { Properties props = System.getProperties();
          props.put("mail.smtp.host", mailhost);
          Session session = Session.getDefaultInstance(props, null);
          Message msg = new MimeMessage(session);
          msg.setFrom(from);
          msg.setRecipients(Message.RecipientType.TO
                          ,InternetAddress.parse(to, false));
          msg.setSubject(subj);
          if(msgType==0) msg.setText(msgbody);
          else msg.setDataHandler(new DataHandler(
                  new ByteArrayDataSource(msgbody, "text/html")));
          msg.setHeader("X-Mailer", "Mailbot");
          msg.setSentDate(new Date());
          Transport.send(msg);
} catch (ThreadDeath e) { res=false; throw e;}
          catch (Exception e) { res=false;}
    return(res);
  }

 class ByteArrayDataSource implements DataSource
 {  private byte[] data;// data
    private String type;// content-type

    /* Create a DataSource from an input stream */
    public ByteArrayDataSource(InputStream is, String type) {
        this.type = type;
        try { 
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            int ch;

            while ((ch = is.read()) != -1)
                // XXX - must be made more efficient by
        // doing buffered reads, rather than one byte reads
        os.write(ch);
    data = os.toByteArray();

        } catch (IOException ioex) { }
    }

    /* Create a DataSource from a byte array */
    public ByteArrayDataSource(byte[] data, String type) {
        this.data = data;
this.type = type;
    }

    /* Create a DataSource from a String */
    public ByteArrayDataSource(String data, String type) {
try {
    // Assumption that the string contains only ASCII
    // characters!  Otherwise just pass a charset into this
    // constructor and use it in getBytes()
    this.data = data.getBytes("iso-8859-1");
} catch (UnsupportedEncodingException uex) { }
this.type = type;
    }

    /**
     * Return an InputStream for the data.
     * Note - a new stream must be returned each time.
     */
    public InputStream getInputStream() throws IOException {
if (data == null)
    throw new IOException("no data");
return new ByteArrayInputStream(data);
    }

    public OutputStream getOutputStream() throws IOException {
throw new IOException("cannot do this");
    }

    public String getContentType() {
        return type;
    }

    public String getName() {
        return "dummy";
    }
  }
}

Полезный коментарий, присланный Serge_B:

В общем случае не будет работать (если заголовок написать по-русски).
Надо так ( точно работает в JavaMail 1.2 ) :
msg.setSubject(subj,"koi8-r");
Телу письма тоже не помешает:
"text/html; charset=koi8-r" вместо "text/html".
И вообще стиль странноватый :-).

Информация взята с сайта Developers.com.ua

 

© журнал принадлежит Web Creation
по всем вопросам обращаться А. Кузьмин