Example usage for javax.mail.internet MimeMessage addHeaderLine

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

Introduction

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

Prototype

@Override
public void addHeaderLine(String line) throws MessagingException 

Source Link

Document

Add a raw RFC 822 header-line.

Usage

From source file:gov.nih.nci.cacis.nav.SendEncryptedMail.java

private MimeMessage encryptMessage(MimeMessage message, Session session, Certificate cert)
        throws NoSuchAlgorithmException, NoSuchProviderException, SMIMEException, MessagingException,
        IOException {//  w w  w.  j a v a 2s. co  m
    /* Create the encrypter */
    final SMIMEEnvelopedGenerator encrypter = new SMIMEEnvelopedGenerator();
    encrypter.addKeyTransRecipient((X509Certificate) cert);

    /* Encrypt the message */
    final MimeBodyPart encryptedPart = encrypter.generate(message, SMIMEEnvelopedGenerator.AES256_CBC,
            PROVIDER_TYPE);

    /*
     * Create a new MimeMessage that contains the encrypted and signed content
     */
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    encryptedPart.writeTo(out);

    final MimeMessage encryptedMessage = new MimeMessage(session, new ByteArrayInputStream(out.toByteArray()));

    /* Set all original MIME headers in the encrypted message */
    final Enumeration headers = message.getAllHeaderLines();
    while (headers.hasMoreElements()) {
        final String headerLine = (String) headers.nextElement();
        /*
         * Make sure not to override any content-* headers from the original message
         */
        if (!Strings.toLowerCase(headerLine).startsWith("content-")) {
            encryptedMessage.addHeaderLine(headerLine);
        }
    }

    return encryptedMessage;
}

From source file:com.sonicle.webtop.mail.Service.java

public Message createMessage(String from, SimpleMessage smsg, List<JsAttachment> attachments, boolean tosave)
        throws Exception {
    MimeMessage msg = null;
    boolean success = true;

    String[] to = SimpleMessage.breakAddr(smsg.getTo());
    String[] cc = SimpleMessage.breakAddr(smsg.getCc());
    String[] bcc = SimpleMessage.breakAddr(smsg.getBcc());
    String replyTo = smsg.getReplyTo();

    msg = new MimeMessage(mainAccount.getMailSession());
    msg.setFrom(getInternetAddress(from));
    InternetAddress ia = null;// w  w  w.ja v a2 s  .c o m

    //set the TO recipient
    for (int q = 0; q < to.length; q++) {
        //        Service.logger.debug("to["+q+"]="+to[q]);
        to[q] = to[q].replace(',', ' ');
        try {
            ia = getInternetAddress(to[q]);
        } catch (AddressException exc) {
            throw new AddressException(to[q]);
        }
        msg.addRecipient(Message.RecipientType.TO, ia);
    }

    //set the CC recipient
    for (int q = 0; q < cc.length; q++) {
        cc[q] = cc[q].replace(',', ' ');
        try {
            ia = getInternetAddress(cc[q]);
        } catch (AddressException exc) {
            throw new AddressException(cc[q]);
        }
        msg.addRecipient(Message.RecipientType.CC, ia);
    }

    //set BCC recipients
    for (int q = 0; q < bcc.length; q++) {
        bcc[q] = bcc[q].replace(',', ' ');
        try {
            ia = getInternetAddress(bcc[q]);
        } catch (AddressException exc) {
            throw new AddressException(bcc[q]);
        }
        msg.addRecipient(Message.RecipientType.BCC, ia);
    }

    //set reply to addr
    if (replyTo != null && replyTo.length() > 0) {
        Address[] replyaddr = new Address[1];
        replyaddr[0] = getInternetAddress(replyTo);
        msg.setReplyTo(replyaddr);
    }

    //add any header
    String headerLines[] = smsg.getHeaderLines();
    for (int i = 0; i < headerLines.length; ++i) {
        if (!headerLines[i].startsWith("Sonicle-reply-folder")) {
            msg.addHeaderLine(headerLines[i]);
        }
    }

    //add reply/references
    String inreplyto = smsg.getInReplyTo();
    String references[] = smsg.getReferences();
    String replyfolder = smsg.getReplyFolder();
    if (inreplyto != null) {
        msg.setHeader("In-Reply-To", inreplyto);
    }
    if (references != null && references[0] != null) {
        msg.setHeader("References", references[0]);
    }
    if (tosave) {
        if (replyfolder != null) {
            msg.setHeader("Sonicle-reply-folder", replyfolder);
        }
        msg.setHeader("Sonicle-draft", "true");
    }

    //add forward data
    String forwardedfrom = smsg.getForwardedFrom();
    String forwardedfolder = smsg.getForwardedFolder();
    if (forwardedfrom != null) {
        msg.setHeader("Forwarded-From", forwardedfrom);
    }
    if (tosave) {
        if (forwardedfolder != null) {
            msg.setHeader("Sonicle-forwarded-folder", forwardedfolder);
        }
        msg.setHeader("Sonicle-draft", "true");
    }
    //set the subject
    String subject = smsg.getSubject();
    try {
        //subject=MimeUtility.encodeText(smsg.getSubject(), "ISO-8859-1", null);
        subject = MimeUtility.encodeText(smsg.getSubject());
    } catch (Exception exc) {
    }
    msg.setSubject(subject);

    //set priority
    int priority = smsg.getPriority();
    if (priority != 3) {
        msg.setHeader("X-Priority", "" + priority);

        //set receipt
    }
    String receiptTo = from;
    try {
        receiptTo = MimeUtility.encodeText(from, "ISO-8859-1", null);
    } catch (Exception exc) {
    }
    if (smsg.getReceipt()) {
        msg.setHeader("Disposition-Notification-To", from);

        //see if there are any new attachments for the message
    }
    int noAttach;
    int newAttach;

    if (attachments == null) {
        newAttach = 0;
    } else {
        newAttach = attachments.size();
    }

    //get the array of the old attachments
    Part[] oldParts = smsg.getAttachments();

    //check if there are old attachments
    if (oldParts == null) {
        noAttach = 0;
    } else { //old attachments exist
        noAttach = oldParts.length;
    }

    if ((newAttach > 0) || (noAttach > 0) || !smsg.getMime().equalsIgnoreCase("text/plain")) {
        // create the main Multipart
        MimeMultipart mp = new MimeMultipart("mixed");
        MimeMultipart unrelated = null;

        String textcontent = smsg.getTextContent();
        //if is text, or no alternative text is available, add the content as one single body part
        //else create a multipart/alternative with both rich and text mime content
        if (textcontent == null || smsg.getMime().equalsIgnoreCase("text/plain")) {
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8"));
            mp.addBodyPart(mbp1);
        } else {
            MimeMultipart alternative = new MimeMultipart("alternative");
            //the rich part
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8"));
            //the text part
            MimeBodyPart mbp1 = new MimeBodyPart();

            /*          ByteArrayOutputStream bos=new ByteArrayOutputStream(textcontent.length());
             com.sun.mail.util.QPEncoderStream qpe=new com.sun.mail.util.QPEncoderStream(bos);
             for(int i=0;i<textcontent.length();++i) {
             try {
             qpe.write(textcontent.charAt(i));
             } catch(IOException exc) {
             Service.logger.error("Exception",exc);
             }
             }
             textcontent=new String(bos.toByteArray());*/
            mbp1.setContent(textcontent, MailUtils.buildPartContentType("text/plain", "UTF-8"));
            //          mbp1.setHeader("Content-transfer-encoding","quoted-printable");

            alternative.addBodyPart(mbp1);
            alternative.addBodyPart(mbp2);

            MimeBodyPart altbody = new MimeBodyPart();
            altbody.setContent(alternative);

            mp.addBodyPart(altbody);
        }

        if (noAttach > 0) { //if there are old attachments
            // create the parts with the attachments
            //MimeBodyPart[] mbps2 = new MimeBodyPart[noAttach];
            //Part[] mbps2 = new Part[noAttach];

            //for(int e = 0;e < noAttach;e++) {
            //  mbps2[e] = (Part)oldParts[e];
            //}//end for e
            //add the old attachment parts
            for (int r = 0; r < noAttach; r++) {
                Object content = null;
                String contentType = null;
                String contentFileName = null;
                if (oldParts[r] instanceof Message) {
                    //                Service.logger.debug("Attachment is a message");
                    Message msgpart = (Message) oldParts[r];
                    MimeMessage mm = new MimeMessage(mainAccount.getMailSession());
                    mm.addFrom(msgpart.getFrom());
                    mm.setRecipients(Message.RecipientType.TO, msgpart.getRecipients(Message.RecipientType.TO));
                    mm.setRecipients(Message.RecipientType.CC, msgpart.getRecipients(Message.RecipientType.CC));
                    mm.setRecipients(Message.RecipientType.BCC,
                            msgpart.getRecipients(Message.RecipientType.BCC));
                    mm.setReplyTo(msgpart.getReplyTo());
                    mm.setSentDate(msgpart.getSentDate());
                    mm.setSubject(msgpart.getSubject());
                    mm.setContent(msgpart.getContent(), msgpart.getContentType());
                    content = mm;
                    contentType = "message/rfc822";
                } else {
                    //                Service.logger.debug("Attachment is not a message");
                    content = oldParts[r].getContent();
                    if (!(content instanceof MimeMultipart)) {
                        contentType = oldParts[r].getContentType();
                        contentFileName = oldParts[r].getFileName();
                    }
                }
                MimeBodyPart mbp = new MimeBodyPart();
                if (contentFileName != null) {
                    mbp.setFileName(contentFileName);
                    //              Service.logger.debug("adding attachment mime "+contentType+" filename "+contentFileName);
                    contentType += "; name=\"" + contentFileName + "\"";
                }
                if (content instanceof MimeMultipart)
                    mbp.setContent((MimeMultipart) content);
                else
                    mbp.setDataHandler(new DataHandler(content, contentType));
                mp.addBodyPart(mbp);
            }

        } //end if, adding old attachments

        if (newAttach > 0) { //if there are new attachments
            // create the parts with the attachments
            MimeBodyPart[] mbps = new MimeBodyPart[newAttach];

            for (int e = 0; e < newAttach; e++) {
                mbps[e] = new MimeBodyPart();

                // attach the file to the message
                JsAttachment attach = (JsAttachment) attachments.get(e);
                UploadedFile upfile = getUploadedFile(attach.uploadId);
                FileDataSource fds = new FileDataSource(upfile.getFile());
                mbps[e].setDataHandler(new DataHandler(fds));
                // filename starts has format:
                // "_" + userid + sessionId + "_" + filename
                //
                if (attach.inline) {
                    mbps[e].setDisposition(Part.INLINE);
                }
                String contentFileName = attach.fileName.trim();
                mbps[e].setFileName(contentFileName);
                String contentType = upfile.getMediaType() + "; name=\"" + contentFileName + "\"";
                mbps[e].setHeader("Content-type", contentType);
                if (attach.cid != null && attach.cid.trim().length() > 0) {
                    mbps[e].setHeader("Content-ID", "<" + attach.cid + ">");
                    mbps[e].setHeader("X-Attachment-Id", attach.cid);
                    mbps[e].setDisposition(Part.INLINE);
                    if (unrelated == null)
                        unrelated = new MimeMultipart("mixed");
                }
            } //end for e

            //add the new attachment parts
            if (unrelated == null) {
                for (int r = 0; r < newAttach; r++)
                    mp.addBodyPart(mbps[r]);
            } else {
                //mp becomes the related part with text parts and cids
                MimeMultipart related = mp;
                related.setSubType("related");
                //nest the related part into the mixed part
                mp = unrelated;
                MimeBodyPart mbd = new MimeBodyPart();
                mbd.setContent(related);
                mp.addBodyPart(mbd);
                for (int r = 0; r < newAttach; r++) {
                    if (mbps[r].getHeader("Content-ID") != null) {
                        related.addBodyPart(mbps[r]);
                    } else {
                        mp.addBodyPart(mbps[r]);
                    }
                }
            }

        } //end if, adding new attachments

        //
        //          msg.addHeaderLine("This is a multi-part message in MIME format.");
        // add the Multipart to the message
        msg.setContent(mp);

    } else { //end if newattach
        msg.setText(smsg.getContent());
    } //singlepart message

    msg.setSentDate(new java.util.Date());

    return msg;

}

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 ww  w .  ja  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.sakaiproject.email.impl.BasicEmailService.java

public void sendMailMessagingException(InternetAddress from, InternetAddress[] to, String subject,
        String content, Map<RecipientType, InternetAddress[]> headerTo, InternetAddress[] replyTo,
        List<String> additionalHeaders, List<Attachment> attachments) throws MessagingException {
    // some timing for debug
    long start = 0;
    if (M_log.isDebugEnabled())
        start = System.currentTimeMillis();

    // if in test mode, use the test method
    if (m_testMode) {
        testSendMail(from, to, subject, content, headerTo, replyTo, additionalHeaders);
        return;/*from   w  ww .j  a va 2  s. c o  m*/
    }

    if (m_smtp == null) {
        M_log.error(
                "Unable to send mail as no smtp server is defined. Please set smtp@org.sakaiproject.email.api.EmailService value in sakai.properties");
        return;
    }

    if (from == null) {
        M_log.warn("sendMail: null from");
        return;
    }

    if (to == null) {
        M_log.warn("sendMail: null to");
        return;
    }

    if (content == null) {
        M_log.warn("sendMail: null content");
        return;
    }

    Properties props = createMailSessionProperties();

    Session session = Session.getInstance(props);

    // see if we have a message-id in the additional headers
    String mid = null;
    if (additionalHeaders != null) {
        for (String header : additionalHeaders) {
            if (header.toLowerCase().startsWith(EmailHeaders.MESSAGE_ID.toLowerCase() + ": ")) {
                // length of 'message-id: ' == 12
                mid = header.substring(12);
                break;
            }
        }
    }

    // use the special extension that can set the id
    MimeMessage msg = new MyMessage(session, mid);

    // the FULL content-type header, for example:
    // Content-Type: text/plain; charset=windows-1252; format=flowed
    String contentTypeHeader = null;

    // If we need to force the container to use a certain multipart subtype
    //    e.g. 'alternative'
    // then sneak it through in the additionalHeaders
    String multipartSubtype = null;

    // set the additional headers on the message
    // but treat Content-Type specially as we need to check the charset
    // and we already dealt with the message id
    if (additionalHeaders != null) {
        for (String header : additionalHeaders) {
            if (header.toLowerCase().startsWith(EmailHeaders.CONTENT_TYPE.toLowerCase() + ": "))
                contentTypeHeader = header;
            else if (header.toLowerCase().startsWith(EmailHeaders.MULTIPART_SUBTYPE.toLowerCase() + ": "))
                multipartSubtype = header.substring(header.indexOf(":") + 1).trim();
            else if (!header.toLowerCase().startsWith(EmailHeaders.MESSAGE_ID.toLowerCase() + ": "))
                msg.addHeaderLine(header);
        }
    }

    // date
    if (msg.getHeader(EmailHeaders.DATE) == null)
        msg.setSentDate(new Date(System.currentTimeMillis()));

    // set the message sender
    msg.setFrom(from);

    // set the message recipients (headers)
    setRecipients(headerTo, msg);

    // set the reply to
    if ((replyTo != null) && (msg.getHeader(EmailHeaders.REPLY_TO) == null))
        msg.setReplyTo(replyTo);

    // update to be Postmaster if necessary
    checkFrom(msg);

    // figure out what charset encoding to use
    //
    // first try to use the charset from the forwarded
    // Content-Type header (if there is one).
    //
    // if that charset doesn't work, try a couple others.
    // the character set, for example, windows-1252 or UTF-8
    String charset = extractCharset(contentTypeHeader);

    if (charset != null && canUseCharset(content, charset) && canUseCharset(subject, charset)) {
        // use the charset from the Content-Type header
    } else if (canUseCharset(content, CharacterSet.ISO_8859_1)
            && canUseCharset(subject, CharacterSet.ISO_8859_1)) {
        if (contentTypeHeader != null && charset != null)
            contentTypeHeader = contentTypeHeader.replaceAll(charset, CharacterSet.ISO_8859_1);
        else if (contentTypeHeader != null)
            contentTypeHeader += "; charset=" + CharacterSet.ISO_8859_1;
        charset = CharacterSet.ISO_8859_1;
    } else if (canUseCharset(content, CharacterSet.WINDOWS_1252)
            && canUseCharset(subject, CharacterSet.WINDOWS_1252)) {
        if (contentTypeHeader != null && charset != null)
            contentTypeHeader = contentTypeHeader.replaceAll(charset, CharacterSet.WINDOWS_1252);
        else if (contentTypeHeader != null)
            contentTypeHeader += "; charset=" + CharacterSet.WINDOWS_1252;
        charset = CharacterSet.WINDOWS_1252;
    } else {
        // catch-all - UTF-8 should be able to handle anything
        if (contentTypeHeader != null && charset != null)
            contentTypeHeader = contentTypeHeader.replaceAll(charset, CharacterSet.UTF_8);
        else if (contentTypeHeader != null)
            contentTypeHeader += "; charset=" + CharacterSet.UTF_8;
        else
            contentTypeHeader = EmailHeaders.CONTENT_TYPE + ": " + ContentType.TEXT_PLAIN + "; charset="
                    + CharacterSet.UTF_8;
        charset = CharacterSet.UTF_8;
    }

    if ((subject != null) && (msg.getHeader(EmailHeaders.SUBJECT) == null))
        msg.setSubject(subject, charset);

    // extract just the content type value from the header
    String contentType = null;
    if (contentTypeHeader != null) {
        int colonPos = contentTypeHeader.indexOf(":");
        contentType = contentTypeHeader.substring(colonPos + 1).trim();
    }
    setContent(content, attachments, msg, contentType, charset, multipartSubtype);

    // if we have a full Content-Type header, set it NOW
    // (after setting the body of the message so that format=flowed is preserved)
    // if there attachments, the messsage type will default to multipart/mixed and should
    // stay that way.
    if ((attachments == null || attachments.size() == 0) && contentTypeHeader != null) {
        msg.addHeaderLine(contentTypeHeader);
        msg.addHeaderLine(EmailHeaders.CONTENT_TRANSFER_ENCODING + ": quoted-printable");
    }

    if (M_log.isDebugEnabled()) {
        M_log.debug("HeaderLines received were: ");
        Enumeration<String> allHeaders = msg.getAllHeaderLines();
        while (allHeaders.hasMoreElements()) {
            M_log.debug((String) allHeaders.nextElement());
        }
    }

    sendMessageAndLog(from, to, subject, headerTo, start, msg, session);
}

From source file:org.sakaiproject.tool.assessment.util.SamigoEmailService.java

public String sendMail() {
    try {//w  w w . j  ava 2s . c  o  m
        Properties props = new Properties();

        // Server
        if (smtpServer == null || smtpServer.equals("")) {
            log.info("samigo.email.smtpServer is not set");
            smtpServer = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService");
            if (smtpServer == null || smtpServer.equals("")) {
                log.info("smtp@org.sakaiproject.email.api.EmailService is not set");
                log.error(
                        "Please set the value of samigo.email.smtpServer or smtp@org.sakaiproject.email.api.EmailService");
                return "error";
            }
        }
        props.setProperty("mail.smtp.host", smtpServer);

        // Port
        if (smtpPort == null || smtpPort.equals("")) {
            log.warn("samigo.email.smtpPort is not set. The default port 25 will be used.");
        } else {
            props.setProperty("mail.smtp.port", smtpPort);
        }

        props.put("mail.smtp.sendpartial", "true");

        Session session = Session.getInstance(props, null);
        session.setDebug(true);
        MimeMessage msg = new MimeMessage(session);

        InternetAddress fromIA = new InternetAddress(fromEmailAddress, fromName);
        msg.setFrom(fromIA);

        //msg.addHeaderLine("Subject: " + subject);
        msg.setSubject(subject, "UTF-8");
        String noReplyEmaillAddress = ServerConfigurationService.getString("setup.request",
                "no-reply@" + ServerConfigurationService.getServerName());
        msg.addHeaderLine("To: " + noReplyEmaillAddress);
        msg.setText(message, "UTF-8");
        msg.addHeaderLine("Content-Type: text/html");

        ArrayList<InternetAddress> toIAList = new ArrayList<InternetAddress>();
        String email = "";
        Iterator iter = toEmailAddressList.iterator();
        while (iter.hasNext()) {
            try {
                email = (String) iter.next();
                toIAList.add(new InternetAddress(email));
            } catch (AddressException ae) {
                log.error("invalid email address: " + email);
            }
        }

        InternetAddress[] toIA = new InternetAddress[toIAList.size()];
        int count = 0;
        Iterator iter2 = toIAList.iterator();
        while (iter2.hasNext()) {
            toIA[count++] = (InternetAddress) iter2.next();
        }

        try {
            Transport transport = session.getTransport("smtp");
            msg.saveChanges();
            transport.connect();

            try {
                transport.sendMessage(msg, toIA);
            } catch (SendFailedException e) {
                log.debug("SendFailedException: " + e);
                return "error";
            } catch (MessagingException e) {
                log.warn("1st MessagingException: " + e);
                return "error";
            }
            transport.close();
        } catch (MessagingException e) {
            log.warn("2nd MessagingException:" + e);
            return "error";
        }

    } catch (UnsupportedEncodingException ue) {
        log.warn("UnsupportedEncodingException:" + ue);
        ue.printStackTrace();

    } catch (MessagingException me) {
        log.warn("3rd MessagingException:" + me);
        return "error";
    }
    return "send";
}