⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mailer.java

📁 利用java发EMAIL的代码.里面有详细注释
💻 JAVA
字号:
package SendMail;
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class Mailer {
  /** The javamail session object. */
  protected Session session;
  /** The sender's email address */
  protected String from;
  /** The subject of the message. */
  protected String subject;
  /** The recipient ("To:"), as Strings. */
  protected ArrayList toList = new ArrayList();
  /** The CC list, as Strings. */
  protected ArrayList ccList = new ArrayList();
  /** The BCC list, as Strings. */
  protected ArrayList bccList = new ArrayList();
  /** The text of the message. */
  protected String body;
  /** The SMTP relay host */
  protected String mailHost;
  /** The accessories list, as Strings.*/
  protected ArrayList accessories = new ArrayList();
  /** The verbosity setting */
  protected boolean verbose;

  /** Get from
   * @return where the mail from
   */
  public String getFrom() {
    return from;
  }

  /** Set from
   * @param fm where the mail from
   */
  public void setFrom(String fm) {
    from = fm;
  }

  /** Get subject
   * @return the mail subject
   */
  public String getSubject() {
    return subject;
  }

  /** Set subject
   * @param subj the mail subject
   */
  public void setSubject(String subj) {
    subject = subj;
  }

  // SETTERS/GETTERS FOR TO: LIST

  /** Get tolist, as an array of Strings
   * @return the list of toAddress
   */
  public ArrayList getToList() {
    return toList;
  }

  /** Set to list to an ArrayList of Strings
   * @param to the list of toAddress
   */
  public void setToList(ArrayList to) {
    toList = to;
  }

  /** Set to as a string like "tom, mary, robin@host". Loses any
   * previously-set values.
   * @param s the list of toAddress*/
  public void setToList(String s) {
    toList = tokenize(s);
  }

  /** Add one "to" recipient
   * @param to the toAddress
   */
  public void addTo(String to) {
    toList.add(to);
  }

  // SETTERS/GETTERS FOR CC: LIST

  /** Get cclist, as an array of Strings
   * @return the list of ccAddress
   */
  public ArrayList getCcList() {
    return ccList;
  }

  /** Set cc list to an ArrayList of Strings
   * @param cc the list of ccAddress
   */
  public void setCcList(ArrayList cc) {
    ccList = cc;
  }

  /** Set cc as a string like "tom, mary, robin@host". Loses any
   * previously-set values.
   * @param s the list of ccAddress
   */
  public void setCcList(String s) {
    ccList = tokenize(s);
  }

  /** Add one "cc" recipient
   * @param cc the address of cc
   */
  public void addCc(String cc) {
    ccList.add(cc);
  }

  // SETTERS/GETTERS FOR BCC: LIST

  /** Get bcclist, as an array of Strings
   * @return the list of bcc
   */
  public ArrayList getBccList() {
    return bccList;
  }

  /** Set bcc list to an ArrayList of Strings
   * @param bcc the address of bcc
   */
  public void setBccList(ArrayList bcc) {
    bccList = bcc;
  }

  /** Set bcc as a string like "tom, mary, robin@host". Loses any
   * previously-set values.
   * @param s the address of bcc
   */
  public void setBccList(String s) {
    bccList = tokenize(s);
  }

  /** Add one "bcc" recipient
   * @param bcc the address of bcc
   */
  public void addBcc(String bcc) {
    bccList.add(bcc);
  }

  // SETTER/GETTER FOR MESSAGE BODY

  /** Get message
   * @return the mail body
   */
  public String getBody() {
    return body;
  }

  /** Set message
   * @param text the mail body
   */
  public void setBody(String text) {
    body = text;
  }

  // SETTER/GETTER FOR ACCESSORIES

  /** Get accessories
   * @return the arrayList of the accessories
   */
  public ArrayList getAccessories() {
    return accessories;
  }

  /** Set accessories
   * @param accessories the arrayList of the accessories
   */
  public void setAccessories(ArrayList accessories) {
    this.accessories = accessories;
  }

  // SETTER/GETTER FOR VERBOSITY

  /** Get verbose
   * @return verbose
   */
  public boolean isVerbose() {
    return verbose;
  }

  /** Set verbose
   * @param v the verbose
   */
  public void setVerbose(boolean v) {
    verbose = v;
  }

  /** Check if all required fields have been set before sending.
   * Normally called e.g., by a JSP before calling doSend.
   * Is also called by doSend for verification.
   * @return if complete return true else return false
   */
  public boolean isComplete() {
    if (from == null || from.length() == 0) {
      System.err.println("doSend: no FROM");
      return false;
    }
    if (subject == null || subject.length() == 0) {
      System.err.println("doSend: no SUBJECT");
      return false;
    }
    if (toList.size() == 0) {
      System.err.println("doSend: no recipients");
      return false;
    }
    if (body == null || body.length() == 0) {
      System.err.println("doSend: no body");
      return false;
    }
    if (mailHost == null || mailHost.length() == 0) {
      System.err.println("doSend: no server host");
      return false;
    }
    return true;
  }

  public void setServer(String s) {
    mailHost = s;
  }

  /** Send the message.
   * @throws MessagingException
   */
  public synchronized void doSend() throws MessagingException {

    if (!isComplete()) {
      throw new IllegalArgumentException(
          "doSend called before message was complete");
    }

    /** Properties object used to pass props into the MAIL API */
    Properties props = new Properties();
    props.put("mail.smtp.host", mailHost);
    System.out.println(mailHost);

    // Create the Session object
    if (session == null) {
      session = Session.getDefaultInstance(props, null);
      if (verbose) {
        session.setDebug(true); // Verbose!
      }
    }

    // create a message
    final Message mesg = new MimeMessage(session);

    InternetAddress[] addresses;

    // TO Address list
    addresses = new InternetAddress[toList.size()];
    for (int i = 0; i < addresses.length; i++) {
      addresses[i] = new InternetAddress( (String) toList.get(i));
    }
    mesg.setRecipients(Message.RecipientType.TO, addresses);

    // From Address
    mesg.setFrom(new InternetAddress(from));

    // CC Address list
    addresses = new InternetAddress[ccList.size()];
    for (int i = 0; i < addresses.length; i++) {
      addresses[i] = new InternetAddress( (String) ccList.get(i));
    }
    mesg.setRecipients(Message.RecipientType.CC, addresses);

    // BCC Address list
    addresses = new InternetAddress[bccList.size()];
    for (int i = 0; i < addresses.length; i++) {
      addresses[i] = new InternetAddress( (String) bccList.get(i));
    }
    mesg.setRecipients(Message.RecipientType.BCC, addresses);

    // The Subject
    mesg.setSubject(subject);

    // Now the message body.
    Multipart mp = new MimeMultipart();
    MimeBodyPart mbp = null;
    mbp = new MimeBodyPart();
    mbp.setText(body);
    mp.addBodyPart(mbp);

    // Now the accessories.
    int accessoriesCount = accessories.size();
    File f;
    DataSource ds;
    String uf;
    int j;
    for (int i = 0; i < accessoriesCount; i++) {
      mbp = new MimeBodyPart();
      f = new File( (String) accessories.get(i));
      ds = new FileDataSource(f);
      mbp.setDataHandler(new DataHandler(ds));
      j = f.getName().lastIndexOf(File.separator);
      uf = f.getName().substring(j + 1);
      mbp.setFileName(uf);
      mp.addBodyPart(mbp);
    }

    mesg.setContent(mp);

    // Finally, send the message! (use static Transport method)
    // Do this in a Thread as it sometimes is too slow for JServ
    // new Thread() {
    // public void run() {
    // try {

    Transport.send(mesg);

    // } catch (MessagingException e) {
    // throw new IllegalArgumentException(
    // "Transport.send() threw: " + e.toString());
    // }
    // }
    // }.start();
  }

  /** Convenience method that does it all with one call.
   * @param mailhost - SMTP server host
   * @param recipient - domain address of email (user@host.domain)
   * @param sender - your email address
   * @param subject - the subject line
   * @param message - the entire message body as a String with embedded \n's
   * @param accessories - the accessories list
   * @throws MessagingException
   */
  public static void send(String mailhost,
                          String recipient, String sender, String subject,
                          String message, ArrayList accessories) throws
      MessagingException {
    Mailer m = new Mailer();
    m.setServer(mailhost);
    m.addTo(recipient);
    m.setFrom(sender);
    m.setSubject(subject);
    m.setBody(message);
    m.setAccessories(accessories);
    m.doSend();
  }

  /** Convert a list of addresses to an ArrayList. This will work
   * for simple names like "tom, mary@foo.com, 123.45@c$.com"
   * but will fail on certain complex (but RFC-valid) names like
   * "(Darwin, Ian) <ian@darwinsys.com>".
   * Or even "Ian Darwin <ian@darwinsys.com>".
   * @param s the string of some list
   * @return the list after split
   */
  protected ArrayList tokenize(String s) {
    ArrayList al = new ArrayList();
    StringTokenizer tf = new StringTokenizer(s, ",");
    // For each word found in the line
    while (tf.hasMoreTokens()) {
      // trim blanks, and add to list.
      al.add(tf.nextToken().trim());
    }
    return al;
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -