Example usage for javax.mail.internet MimeMessage removeHeader

List of usage examples for javax.mail.internet MimeMessage removeHeader

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage removeHeader.

Prototype

@Override
public void removeHeader(String name) throws MessagingException 

Source Link

Document

Remove all headers with this name.

Usage

From source file:com.duroty.application.files.manager.SendMessageThread.java

/**
 * <p>/*  w ww . ja  v  a 2 s.  c  om*/
 * Implementation of Thread.run()
 * </p>
 */
public void start() throws Exception {
    try {
        if (email != null) {
            email.getMimeMessage().removeHeader("X-DBox");
            email.send();

            return;
        }

        if (mime != null) {
            mime.removeHeader("X-DBox");
            Transport.send(mime);

            return;
        }

        if (mimes != null) {
            for (int i = 0; i < mimes.size(); i++) {
                MimeMessage mm = (MimeMessage) mimes.get(i);
                mm.removeHeader("X-DBox");
                Transport.send(mm);
            }
        }
    } catch (Exception ex) {
        throw new MailException(ex);
    } catch (java.lang.OutOfMemoryError ex) {
        System.gc();
        throw new MailException(ex);
    } catch (Throwable ex) {
        throw new MailException(ex);
    } finally {
        System.gc();
    }
}

From source file:hudson.tasks.MailSender.java

public boolean execute(AbstractBuild<?, ?> build, BuildListener listener) throws InterruptedException {
    try {/*  w ww  .j a v  a2s.  co m*/
        MimeMessage mail = getMail(build, listener);
        if (mail != null) {
            // if the previous e-mail was sent for a success, this new e-mail
            // is not a follow up
            AbstractBuild<?, ?> pb = build.getPreviousBuild();
            if (pb != null && pb.getResult() == Result.SUCCESS) {
                mail.removeHeader("In-Reply-To");
                mail.removeHeader("References");
            }

            Address[] allRecipients = mail.getAllRecipients();
            if (allRecipients != null) {
                StringBuilder buf = new StringBuilder("Sending e-mails to:");
                for (Address a : allRecipients)
                    buf.append(' ').append(a);
                listener.getLogger().println(buf);
                Transport.send(mail);

                build.addAction(new MailMessageIdAction(mail.getMessageID()));
            } else {
                listener.getLogger().println(Messages.MailSender_ListEmpty());
            }
        }
    } catch (MessagingException e) {
        e.printStackTrace(listener.error(e.getMessage()));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace(listener.error(e.getMessage()));
    } finally {
        CHECKPOINT.report();
    }

    return true;
}

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

/**
 * DOCUMENT ME!/*from ww  w  .  j  av a2  s.  c o m*/
 *
 * @param message DOCUMENT ME!
 *
 * @throws javax.mail.MessagingException DOCUMENT ME!
 */
public static void clearAllHeaders(MimeMessage message) throws javax.mail.MessagingException {
    Enumeration headers = message.getAllHeaders();

    while (headers.hasMoreElements()) {
        Header header = (Header) headers.nextElement();

        try {
            message.removeHeader(header.getName());
        } catch (javax.mail.MessagingException me) {
        }
    }

    message.saveChanges();
}

From source file:immf.ImodeForwardMail.java

@Override
public void buildMimeMessage() throws EmailException {
    super.buildMimeMessage();
    MimeMessage msg = this.getMimeMessage();
    try {//from   w ww . j a  va 2 s.co m
        msg.setHeader("X-Mailer", ServerMain.Version);

        if (!this.conf.isRewriteAddress()) {
            // ??imode????????
            msg.setHeader("Resent-From", this.conf.getSmtpMailAddress());
            if (!this.conf.getForwardTo().isEmpty()) {
                msg.setHeader("Resent-To", StringUtils.join(this.conf.getForwardTo(), ","));
            }
            if (!this.conf.getForwardCc().isEmpty()) {
                msg.setHeader("Resent-Cc", StringUtils.join(this.conf.getForwardCc(), ","));
            }
            if (!this.conf.getForwardBcc().isEmpty()) {
                msg.setHeader("Resent-Bcc", StringUtils.join(this.conf.getForwardBcc(), ","));
            }
            SimpleDateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z (z)", Locale.US);
            msg.setHeader("Resent-Date", df.format(new Date()));
            msg.setHeader("Date", df.format(this.imm.getTimeDate()));

            msg.removeHeader("To");
            msg.removeHeader("Cc");
            msg.removeHeader("Bcc");

            List<InternetAddress> tolist = new ArrayList<InternetAddress>();
            List<InternetAddress> cclist = new ArrayList<InternetAddress>();

            boolean useMyAddress = false;
            if (this.imm.getFolderId() != ImodeNetClient.FolderIdSent) {
                if (this.conf.isHideMyaddr()) {
                    if (this.imm.getToAddrList().size() == 0) {
                        useMyAddress = true;
                    }
                } else {
                    useMyAddress = true;
                }
            }
            if (useMyAddress) {
                switch (this.imm.getRecvType()) {
                case ImodeMail.RECV_TYPE_TO:
                    tolist.add(this.imm.getMyInternetAddress());
                    break;
                case ImodeMail.RECV_TYPE_CC:
                    cclist.add(this.imm.getMyInternetAddress());
                    break;
                case ImodeMail.RECV_TYPE_BCC:
                    break;
                }
            }
            tolist.addAll(this.imm.getToAddrList());
            cclist.addAll(this.imm.getCcAddrList());

            msg.setHeader("To", InternetAddress.toString(tolist.toArray(new InternetAddress[0])));

            if (this.imm.getCcAddrList().size() > 0) {
                msg.setHeader("Cc", InternetAddress.toString(cclist.toArray(new InternetAddress[0])));
            }

            msg.setFrom(this.imm.getFromAddr());
        }

        String subject = null;
        if (imm.getFolderId() == ImodeNetClient.FolderIdSent) {
            subject = conf.getSentSubjectAppendPrefix() + imm.getSubject() + conf.getSentSubjectAppendSuffix();
        } else {
            subject = conf.getSubjectAppendPrefix() + imm.getSubject() + conf.getSubjectAppendSuffix();
        }
        if (conf.isSubjectEmojiReplace()) {
            subject = EmojiUtil.replaceToLabel(subject);
        }

        if (ImodeForwardMail.goomojiSubjectCharConv != null) {
            String goomojiSubject = ImodeForwardMail.goomojiSubjectCharConv.convert(subject);
            msg.setHeader("X-Goomoji-Source", "docomo_ne_jp");
            msg.setHeader("X-Goomoji-Subject", Util.encodeGoomojiSubject(goomojiSubject));
        }

        subject = ImodeForwardMail.subjectCharConv.convert(subject);
        msg.setSubject(MimeUtility.encodeText(subject, this.charset, "B"));

        if (this.conf.getContentTransferEncoding() != null) {
            msg.setHeader("Content-Transfer-Encoding", this.conf.getContentTransferEncoding());
        }

    } catch (Exception e) {
        log.warn(e);
    }
}

From source file:davmail.exchange.ExchangeSession.java

protected void convertResentHeader(MimeMessage mimeMessage, String headerName) throws MessagingException {
    String[] resentHeader = mimeMessage.getHeader("Resent-" + headerName);
    if (resentHeader != null) {
        mimeMessage.removeHeader("Resent-" + headerName);
        mimeMessage.removeHeader(headerName);
        for (String value : resentHeader) {
            mimeMessage.addHeader(headerName, value);
        }//from  w  w w  . ja  v  a 2  s. c om
    }
}

From source file:davmail.exchange.ExchangeSession.java

/**
 * Send message in reader to recipients.
 * Detect visible recipients in message body to determine bcc recipients
 *
 * @param rcptToRecipients recipients list
 * @param mimeMessage      mime message/*from  w  w w  . ja  v  a 2 s. c om*/
 * @throws IOException        on error
 * @throws MessagingException on error
 */
public void sendMessage(List<String> rcptToRecipients, MimeMessage mimeMessage)
        throws IOException, MessagingException {
    // detect duplicate send command
    String messageId = mimeMessage.getMessageID();
    if (lastSentMessageId != null && lastSentMessageId.equals(messageId)) {
        LOGGER.debug("Dropping message id " + messageId + ": already sent");
        return;
    }
    lastSentMessageId = messageId;

    convertResentHeader(mimeMessage, "From");
    convertResentHeader(mimeMessage, "To");
    convertResentHeader(mimeMessage, "Cc");
    convertResentHeader(mimeMessage, "Bcc");
    convertResentHeader(mimeMessage, "Message-Id");

    mimeMessage.removeHeader("From");

    // remove visible recipients from list
    Set<String> visibleRecipients = new HashSet<String>();
    List<InternetAddress> recipients = getAllRecipients(mimeMessage);
    for (InternetAddress address : recipients) {
        visibleRecipients.add((address.getAddress().toLowerCase()));
    }
    for (String recipient : rcptToRecipients) {
        if (!visibleRecipients.contains(recipient.toLowerCase())) {
            mimeMessage.addRecipient(javax.mail.Message.RecipientType.BCC, new InternetAddress(recipient));
        }
    }
    sendMessage(mimeMessage);

}

From source file:org.apache.james.jdkim.mailets.DKIMSign.java

@SuppressWarnings("unchecked")
private void prependHeader(MimeMessage message, String signatureHeader) throws MessagingException {
    List<String> prevHeader = new LinkedList<String>();
    // read all the headers
    for (Enumeration<String> e = message.getAllHeaderLines(); e.hasMoreElements();) {
        String headerLine = e.nextElement();
        prevHeader.add(headerLine);/*from www .j  a v  a 2s. c o  m*/
    }
    // remove all the headers
    for (Enumeration<Header> e = message.getAllHeaders(); e.hasMoreElements();) {
        Header header = e.nextElement();
        message.removeHeader(header.getName());
    }
    // add our header
    message.addHeaderLine(signatureHeader);
    // add the remaining headers using "addHeaderLine" that won't alter the
    // insertion order.
    for (Iterator<String> i = prevHeader.iterator(); i.hasNext();) {
        String header = i.next();
        message.addHeaderLine(header);
    }
}

From source file:org.apache.james.transport.mailets.delivery.MailDispatcher.java

private List<String> removeDeliveryHeaders(MimeMessage message) throws MessagingException {
    List<String> deliveredToHeader = Arrays
            .asList(Optional.fromNullable(message.getHeader(DELIVERED_TO)).or(NO_HEADERS));
    message.removeHeader(DELIVERED_TO);
    return deliveredToHeader;
}

From source file:org.apache.james.transport.mailets.delivery.MailDispatcher.java

private Collection<MailAddress> deliver(Mail mail, MimeMessage message) {
    Collection<MailAddress> errors = new Vector<MailAddress>();
    for (MailAddress recipient : mail.getRecipients()) {
        try {/*from   w  w  w  . ja va2s .c o  m*/
            // Add qmail's de facto standard Delivered-To header
            message.addHeader(DELIVERED_TO, recipient.toString());
            mailStore.storeMail(recipient, mail);
            message.removeHeader(DELIVERED_TO);
        } catch (Exception ex) {
            log.error("Error while storing mail.", ex);
            errors.add(recipient);
        }
    }
    return errors;
}

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

/**
 * Delivers a mail to a local mailbox./*from   www  . j  a  v a  2 s. com*/
 * 
 * @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);
    }
}