Example usage for javax.mail.internet InternetHeaders getAllHeaders

List of usage examples for javax.mail.internet InternetHeaders getAllHeaders

Introduction

In this page you can find the example usage for javax.mail.internet InternetHeaders getAllHeaders.

Prototype

public Enumeration<Header> getAllHeaders() 

Source Link

Document

Return all the headers as an Enumeration of javax.mail.Header objects.

Usage

From source file:com.adaptris.core.services.mime.FlattenMimeParts.java

private void addHeaders(InternetHeaders hdrs, MultiPartOutput out) {
    Enumeration e = hdrs.getAllHeaders();
    while (e.hasMoreElements()) {
        Header h = (Header) e.nextElement();
        if (!DISCARD.contains(h.getName().toLowerCase())) {
            out.setHeader(h.getName(), h.getValue());
        }//from   w w w. j  ava2 s. co m
    }
}

From source file:com.trsst.server.AbstractMultipartAdapter.java

private Map<String, String> getHeaders(MultipartInputStream multipart) throws IOException, MessagingException {
    Map<String, String> mapHeaders = new HashMap<String, String>();
    moveToHeaders(multipart);// w  ww .j  a v a2s . c o m
    InternetHeaders headers = new InternetHeaders(multipart);

    Enumeration<Header> allHeaders = headers.getAllHeaders();
    if (allHeaders != null) {
        while (allHeaders.hasMoreElements()) {
            Header header = allHeaders.nextElement();
            mapHeaders.put(header.getName().toLowerCase(), header.getValue());
        }
    }

    return mapHeaders;
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * DOCUMENT ME!//from  ww  w  . j  ava  2 s  . c o  m
 *
 * @param message DOCUMENT ME!
 * @param headers DOCUMENT ME!
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static void addHeaders(Message message, InternetHeaders headers) throws MessagingException {
    Header xheader;
    Enumeration xe = headers.getAllHeaders();

    for (; xe.hasMoreElements();) {
        xheader = (Header) xe.nextElement();
        message.addHeader(xheader.getName(), xheader.getValue());
    }
}

From source file:com.duroty.application.mail.manager.SendManager.java

/**
 * DOCUMENT ME!//w  w  w  . j av  a  2s  .  c om
 *
 * @param hsession DOCUMENT ME!
 * @param session DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param ideIdint DOCUMENT ME!
 * @param to DOCUMENT ME!
 * @param cc DOCUMENT ME!
 * @param bcc DOCUMENT ME!
 * @param subject DOCUMENT ME!
 * @param body DOCUMENT ME!
 * @param attachments DOCUMENT ME!
 * @param isHtml DOCUMENT ME!
 * @param charset DOCUMENT ME!
 * @param headers DOCUMENT ME!
 * @param priority DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public void saveDraft(org.hibernate.Session hsession, Session session, String repositoryName, int ideIdint,
        String to, String cc, String bcc, String subject, String body, Vector attachments, boolean isHtml,
        String charset, InternetHeaders headers, String priority) throws MailException {
    try {
        if (charset == null) {
            charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName());
        }

        if ((body == null) || body.trim().equals("")) {
            body = " ";
        }

        Email email = null;

        if (isHtml) {
            email = new HtmlEmail();
        } else {
            email = new MultiPartEmail();
        }

        email.setCharset(charset);

        Users user = getUser(hsession, repositoryName);
        Identity identity = getIdentity(hsession, ideIdint, user);

        InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName());
        InternetAddress[] _to = MessageUtilities.encodeAddresses(to, null);
        InternetAddress[] _cc = MessageUtilities.encodeAddresses(cc, null);
        InternetAddress[] _bcc = MessageUtilities.encodeAddresses(bcc, null);

        if (_from != null) {
            email.setFrom(_from.getAddress(), _from.getPersonal());
        }

        if (_returnPath != null) {
            email.addHeader("Return-Path", _returnPath.getAddress());
            email.addHeader("Errors-To", _returnPath.getAddress());
            email.addHeader("X-Errors-To", _returnPath.getAddress());
        }

        if (_replyTo != null) {
            email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal());
        }

        if ((_to != null) && (_to.length > 0)) {
            HashSet aux = new HashSet(_to.length);
            Collections.addAll(aux, _to);
            email.setTo(aux);
        }

        if ((_cc != null) && (_cc.length > 0)) {
            HashSet aux = new HashSet(_cc.length);
            Collections.addAll(aux, _cc);
            email.setCc(aux);
        }

        if ((_bcc != null) && (_bcc.length > 0)) {
            HashSet aux = new HashSet(_bcc.length);
            Collections.addAll(aux, _bcc);
            email.setBcc(aux);
        }

        email.setSubject(subject);

        Date now = new Date();

        email.setSentDate(now);

        File dir = new File(System.getProperty("user.home") + File.separator + "tmp");
        if (!dir.exists()) {
            dir.mkdir();
        }

        if ((attachments != null) && (attachments.size() > 0)) {
            for (int i = 0; i < attachments.size(); i++) {
                ByteArrayInputStream bais = null;
                FileOutputStream fos = null;

                try {
                    MailPartObj obj = (MailPartObj) attachments.get(i);

                    File file = new File(dir, obj.getName());

                    bais = new ByteArrayInputStream(obj.getAttachent());
                    fos = new FileOutputStream(file);
                    IOUtils.copy(bais, fos);

                    EmailAttachment attachment = new EmailAttachment();
                    attachment.setPath(file.getPath());
                    attachment.setDisposition(EmailAttachment.ATTACHMENT);
                    attachment.setDescription("File Attachment: " + file.getName());
                    attachment.setName(file.getName());

                    if (email instanceof MultiPartEmail) {
                        ((MultiPartEmail) email).attach(attachment);
                    }
                } catch (Exception ex) {

                } finally {
                    IOUtils.closeQuietly(bais);
                    IOUtils.closeQuietly(fos);
                }
            }
        }

        if (headers != null) {
            Header xheader;
            Enumeration xe = headers.getAllHeaders();

            for (; xe.hasMoreElements();) {
                xheader = (Header) xe.nextElement();

                if (xheader.getName().equals(RFC2822Headers.IN_REPLY_TO)) {
                    email.addHeader(xheader.getName(), xheader.getValue());
                } else if (xheader.getName().equals(RFC2822Headers.REFERENCES)) {
                    email.addHeader(xheader.getName(), xheader.getValue());
                }
            }
        }

        if (priority != null) {
            if (priority.equals("high")) {
                email.addHeader("Importance", priority);
                email.addHeader("X-priority", "1");
            } else if (priority.equals("low")) {
                email.addHeader("Importance", priority);
                email.addHeader("X-priority", "5");
            }
        }

        if (email instanceof HtmlEmail) {
            ((HtmlEmail) email).setHtmlMsg(body);
        } else {
            email.setMsg(body);
        }

        email.setMailSession(session);

        email.buildMimeMessage();

        MimeMessage mime = email.getMimeMessage();
        int size = MessageUtilities.getMessageSize(mime);

        if (!controlQuota(hsession, user, size)) {
            throw new MailException("ErrorMessages.mail.quota.exceded");
        }

        messageable.storeDraftMessage(getId(), mime, user);
    } catch (MailException e) {
        throw e;
    } catch (Exception e) {
        throw new MailException(e);
    } catch (java.lang.OutOfMemoryError ex) {
        System.gc();
        throw new MailException(ex);
    } catch (Throwable e) {
        throw new MailException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.duroty.application.mail.manager.SendManager.java

/**
 * DOCUMENT ME!//from  w w w . j  ava2 s . c  om
 *
 * @param hsession DOCUMENT ME!
 * @param session DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param identity DOCUMENT ME!
 * @param to DOCUMENT ME!
 * @param cc DOCUMENT ME!
 * @param bcc DOCUMENT ME!
 * @param subject DOCUMENT ME!
 * @param body DOCUMENT ME!
 * @param attachments DOCUMENT ME!
 * @param isHtml DOCUMENT ME!
 * @param charset DOCUMENT ME!
 * @param headers DOCUMENT ME!
 * @param priority DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public void send(org.hibernate.Session hsession, Session session, String repositoryName, int ideIdint,
        String to, String cc, String bcc, String subject, String body, Vector attachments, boolean isHtml,
        String charset, InternetHeaders headers, String priority) throws MailException {
    try {
        if (charset == null) {
            charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName());
        }

        if ((body == null) || body.trim().equals("")) {
            body = " ";
        }

        Email email = null;

        if (isHtml) {
            email = new HtmlEmail();
        } else {
            email = new MultiPartEmail();
        }

        email.setCharset(charset);

        Users user = getUser(hsession, repositoryName);
        Identity identity = getIdentity(hsession, ideIdint, user);

        InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName());
        InternetAddress[] _to = MessageUtilities.encodeAddresses(to, null);
        InternetAddress[] _cc = MessageUtilities.encodeAddresses(cc, null);
        InternetAddress[] _bcc = MessageUtilities.encodeAddresses(bcc, null);

        if (_from != null) {
            email.setFrom(_from.getAddress(), _from.getPersonal());
        }

        if (_returnPath != null) {
            email.addHeader("Return-Path", _returnPath.getAddress());
            email.addHeader("Errors-To", _returnPath.getAddress());
            email.addHeader("X-Errors-To", _returnPath.getAddress());
        }

        if (_replyTo != null) {
            email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal());
        }

        if ((_to != null) && (_to.length > 0)) {
            HashSet aux = new HashSet(_to.length);
            Collections.addAll(aux, _to);
            email.setTo(aux);
        }

        if ((_cc != null) && (_cc.length > 0)) {
            HashSet aux = new HashSet(_cc.length);
            Collections.addAll(aux, _cc);
            email.setCc(aux);
        }

        if ((_bcc != null) && (_bcc.length > 0)) {
            HashSet aux = new HashSet(_bcc.length);
            Collections.addAll(aux, _bcc);
            email.setBcc(aux);
        }

        email.setSubject(subject);

        Date now = new Date();

        email.setSentDate(now);

        File dir = new File(System.getProperty("user.home") + File.separator + "tmp");
        if (!dir.exists()) {
            dir.mkdir();
        }

        if ((attachments != null) && (attachments.size() > 0)) {
            for (int i = 0; i < attachments.size(); i++) {
                ByteArrayInputStream bais = null;
                FileOutputStream fos = null;

                try {
                    MailPartObj obj = (MailPartObj) attachments.get(i);

                    File file = new File(dir, obj.getName());

                    bais = new ByteArrayInputStream(obj.getAttachent());
                    fos = new FileOutputStream(file);
                    IOUtils.copy(bais, fos);

                    EmailAttachment attachment = new EmailAttachment();
                    attachment.setPath(file.getPath());
                    attachment.setDisposition(EmailAttachment.ATTACHMENT);
                    attachment.setDescription("File Attachment: " + file.getName());
                    attachment.setName(file.getName());

                    if (email instanceof MultiPartEmail) {
                        ((MultiPartEmail) email).attach(attachment);
                    }
                } catch (Exception ex) {

                } finally {
                    IOUtils.closeQuietly(bais);
                    IOUtils.closeQuietly(fos);
                }
            }
        }

        String mid = getId();

        if (headers != null) {
            Header xheader;
            Enumeration xe = headers.getAllHeaders();

            for (; xe.hasMoreElements();) {
                xheader = (Header) xe.nextElement();

                if (xheader.getName().equals(RFC2822Headers.IN_REPLY_TO)) {
                    email.addHeader(xheader.getName(), xheader.getValue());
                } else if (xheader.getName().equals(RFC2822Headers.REFERENCES)) {
                    email.addHeader(xheader.getName(), xheader.getValue());
                }
            }
        } else {
            email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">");
            email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">");
        }

        if (priority != null) {
            if (priority.equals("high")) {
                email.addHeader("Importance", priority);
                email.addHeader("X-priority", "1");
            } else if (priority.equals("low")) {
                email.addHeader("Importance", priority);
                email.addHeader("X-priority", "5");
            }
        }

        if (email instanceof HtmlEmail) {
            ((HtmlEmail) email).setHtmlMsg(body);
        } else {
            email.setMsg(body);
        }

        email.setMailSession(session);

        email.buildMimeMessage();

        MimeMessage mime = email.getMimeMessage();

        int size = MessageUtilities.getMessageSize(mime);

        if (!controlQuota(hsession, user, size)) {
            throw new MailException("ErrorMessages.mail.quota.exceded");
        }

        messageable.saveSentMessage(mid, mime, user);

        Thread thread = new Thread(new SendMessageThread(email));
        thread.start();
    } catch (MailException e) {
        throw e;
    } catch (Exception e) {
        throw new MailException(e);
    } catch (java.lang.OutOfMemoryError ex) {
        System.gc();
        throw new MailException(ex);
    } catch (Throwable e) {
        throw new MailException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:org.apache.jsieve.mailet.SieveMailboxMailet.java

/**
 * Delivers a mail to a local mailbox.// w  ww  . j  a  v  a2  s.  c  o  m
 * 
 * @param mail
 *            the mail being processed
 * 
 * @throws MessagingException
 *             if an error occurs while storing the mail
 */
@SuppressWarnings("unchecked")
@Override
public void service(Mail mail) throws MessagingException {
    Collection<MailAddress> recipients = mail.getRecipients();
    Collection<MailAddress> errors = new Vector<MailAddress>();

    MimeMessage message = null;
    if (deliveryHeader != null || resetReturnPath) {
        message = mail.getMessage();
    }

    if (resetReturnPath) {
        // Set Return-Path and remove all other Return-Path headers from the
        // message
        // This only works because there is a placeholder inserted by
        // MimeMessageWrapper
        message.setHeader(RFC2822Headers.RETURN_PATH,
                (mail.getSender() == null ? "<>" : "<" + mail.getSender() + ">"));
    }

    Enumeration headers;
    InternetHeaders deliveredTo = new InternetHeaders();
    if (deliveryHeader != null) {
        // Copy any Delivered-To headers from the message
        headers = message.getMatchingHeaders(new String[] { deliveryHeader });
        while (headers.hasMoreElements()) {
            Header header = (Header) headers.nextElement();
            deliveredTo.addHeader(header.getName(), header.getValue());
        }
    }

    for (Iterator<MailAddress> i = recipients.iterator(); i.hasNext();) {
        MailAddress recipient = i.next();
        try {
            if (deliveryHeader != null) {
                // Add qmail's de facto standard Delivered-To header
                message.addHeader(deliveryHeader, recipient.toString());
            }

            storeMail(mail.getSender(), recipient, mail);

            if (deliveryHeader != null) {
                if (i.hasNext()) {
                    // Remove headers but leave all placeholders
                    message.removeHeader(deliveryHeader);
                    headers = deliveredTo.getAllHeaders();
                    // And restore any original Delivered-To headers
                    while (headers.hasMoreElements()) {
                        Header header = (Header) headers.nextElement();
                        message.addHeader(header.getName(), header.getValue());
                    }
                }
            }
        } catch (Exception ex) {
            log("Error while storing mail.", ex);
            errors.add(recipient);
        }
    }

    if (!errors.isEmpty()) {
        // If there were errors, we redirect the email to the ERROR
        // processor.
        // In order for this server to meet the requirements of the SMTP
        // specification, mails on the ERROR processor must be returned to
        // the sender. Note that this email doesn't include any details
        // regarding the details of the failure(s).
        // In the future we may wish to address this.
        getMailetContext().sendMail(mail.getSender(), errors, mail.getMessage(), Mail.ERROR);
    }
    if (consume) {
        // Consume this message
        mail.setState(Mail.GHOST);
    }
}

From source file:org.openhim.mediator.normalization.XDSbMimeProcessorActor.java

private Enumeration createCopyOfHeaders(BodyPart part) throws MessagingException {
    Enumeration headers = part.getAllHeaders();
    InternetHeaders internetHeaders = new InternetHeaders();
    while (headers.hasMoreElements()) {
        Header header = (Header) headers.nextElement();
        internetHeaders.addHeader(header.getName(), header.getValue());
    }//from  w w w .  ja  va 2 s  .co  m
    return internetHeaders.getAllHeaders();
}

From source file:org.sakaiproject.nakamura.smtp.SakaiSmtpServer.java

@SuppressWarnings("unchecked")
private Content writeMessage(Session session, Map<String, Object> mapProperties, InputStream data,
        String storePath)// ww  w. j  av a2  s  .  co  m
        throws MessagingException, AccessDeniedException, StorageClientException, IOException {
    InternetHeaders internetHeaders = new InternetHeaders(data);
    // process the headers into a map.
    for (Enumeration<Header> e = internetHeaders.getAllHeaders(); e.hasMoreElements();) {
        Header h = e.nextElement();
        String name = h.getName();
        String[] values = internetHeaders.getHeader(name);
        if (values != null) {
            if (values.length == 1) {
                mapProperties.put("sakai:" + name.toLowerCase(), values[0]);
            } else {
                mapProperties.put("sakai:" + name.toLowerCase(), values);
            }
        }
    }
    String[] contentType = internetHeaders.getHeader("content-type");
    if (contentType != null && contentType.length > 0 && contentType[0].contains("boundary")
            && contentType[0].contains("multipart/")) {
        MimeMultipart multipart = new MimeMultipart(new SMTPDataSource(contentType[0], data));
        Content message = messagingService.create(session, mapProperties,
                (String) mapProperties.get("sakai:message-id"), storePath);
        writeMultipartToNode(session, message, multipart);
        return message;
    } else {
        Content node = messagingService.create(session, mapProperties);
        // set up to stream the body.
        session.getContentManager().writeBody(node.getPath(), data);
        return node;
    }
}