示例#1
0
  public void send() {

    Properties props = new Properties();

    props.setProperty("mail.transport.protocol", "smtp");
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    Session mailSession = Session.getDefaultInstance(props);
    // mailSession.setDebug(true);
    Transport transport;
    try {
      transport = mailSession.getTransport();

      MimeMessage message = new MimeMessage(mailSession);
      message.setFrom(new InternetAddress(userName));
      message.setSubject(subject);

      message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

      if (!cc.equals("")) {
        message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
      }
      if (!bcc.equals("")) {
        message.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc));
      }

      // create the message part
      MimeBodyPart messageBodyPart = new MimeBodyPart();

      // fill message
      messageBodyPart.setText(content);

      Multipart multipart = new MimeMultipart();
      multipart.addBodyPart(messageBodyPart);
      if (fList != null) {
        Iterator<File> i = fList.iterator();
        // part two is attachment
        while (i.hasNext()) {
          File file = (File) i.next();
          messageBodyPart = new MimeBodyPart();
          DataSource source = new FileDataSource(file);
          messageBodyPart.setDataHandler(new DataHandler(source));
          messageBodyPart.setFileName(file.getName());
          multipart.addBodyPart(messageBodyPart);
        }
      }
      // Put parts in message
      message.setContent(multipart);

      Transport.send(message);

      transport.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }