Exemplo n.º 1
0
  public void send(MailMessage mail) throws MailSenderException {
    verify(mail);

    try {
      SimpleMailMessage message = new SimpleMailMessage(getSmtpHost(), getSmtpPort());

      message.from(mail.getFrom().getRfc2822Address());

      for (Iterator iter = mail.getToAddresses().iterator(); iter.hasNext(); ) {
        message.to(((MailMessage.Address) iter.next()).getRfc2822Address());
      }

      for (Iterator iter = mail.getCcAddresses().iterator(); iter.hasNext(); ) {
        message.cc(((MailMessage.Address) iter.next()).getRfc2822Address());
      }

      for (Iterator iter = mail.getBccAddresses().iterator(); iter.hasNext(); ) {
        message.bcc(((MailMessage.Address) iter.next()).getRfc2822Address());
      }

      message.setSubject(mail.getSubject());

      for (Iterator it = mail.getHeaders().entrySet().iterator(); it.hasNext(); ) {
        Map.Entry entry = (Map.Entry) it.next();

        Object value = entry.getValue();
        if (value instanceof List) {
          for (Iterator values = ((List) value).iterator(); values.hasNext(); ) {
            String content = (String) values.next();
            message.setHeader(entry.getKey().toString(), StringUtils.clean(content));
          }
        } else {
          String content = (String) value;
          message.setHeader(entry.getKey().toString(), StringUtils.clean(content));
        }
      }

      if (mail.getSendDate() != null) {
        message.setHeader("Date", DateFormatUtils.getDateHeader(mail.getSendDate()));
      } else {
        message.setHeader("Date", DateFormatUtils.getDateHeader(new Date()));
      }

      message.getPrintStream().print(mail.getContent());

      message.sendAndClose();
    } catch (IOException ex) {
      throw new MailSenderException("Error while sending mail.", ex);
    }
  }