Example usage for javax.mail.internet MimeMessage writeTo

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

Introduction

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

Prototype

public void writeTo(OutputStream os, String[] ignoreList) throws IOException, MessagingException 

Source Link

Document

Output the message as an RFC 822 format stream, without specified headers.

Usage

From source file:org.apache.axis.attachments.MimeUtils.java

/**
 * This routine will the multi part type and write it out to a stream.
 *
 * <p>Note that is does *NOT* pass <code>AxisProperties</code>
 * to <code>javax.mail.Session.getInstance</code>, but instead
 * the System properties.//from   w  w  w . j  av a 2 s. c  om
 * </p>
 * @param os is the output stream to write to.
 * @param mp the multipart that needs to be written to the stream.
 */
public static void writeToMultiPartStream(java.io.OutputStream os, javax.mail.internet.MimeMultipart mp) {

    try {
        Properties props = AxisProperties.getProperties();

        props.setProperty("mail.smtp.host", "localhost"); // this is a bogus since we will never mail it.

        javax.mail.Session session = javax.mail.Session.getInstance(props, null);
        javax.mail.internet.MimeMessage message = new javax.mail.internet.MimeMessage(session);

        message.setContent(mp);
        message.saveChanges();
        message.writeTo(os, filter);
    } catch (javax.mail.MessagingException e) {
        log.error(Messages.getMessage("javaxMailMessagingException00"), e);
    } catch (java.io.IOException e) {
        log.error(Messages.getMessage("javaIOException00"), e);
    }
}

From source file:se.inera.axel.shs.processor.ShsMessageMarshaller.java

public void marshal(ShsMessage shsMessage, OutputStream outputStream) throws IllegalMessageStructureException {
    log.trace("marshal(ShsMessage, OutputStream)");

    MimeMultipart multipart = new MimeMultipart();
    BodyPart bodyPart = new MimeBodyPart();

    try {/*from ww w.j  ava 2  s.  c o m*/

        ShsLabel label = shsMessage.getLabel();
        if (label == null) {
            throw new IllegalMessageStructureException("label not found in shs message");
        }

        Content content = label.getContent();
        if (content == null) {
            throw new IllegalMessageStructureException("label/content not found in shs label");
        } else {
            // we will update this according to our data parts below.
            content.getDataOrCompound().clear();

            String contentId = content.getContentId();
            content.setContentId(contentId.substring(0, Math.min(contentId.length(), MAX_LENGTH_CONTENT_ID)));
        }

        List<DataPart> dataParts = shsMessage.getDataParts();

        if (dataParts.isEmpty()) {
            throw new IllegalMessageStructureException("dataparts not found in message");
        }

        for (DataPart dp : dataParts) {
            Data data = new Data();

            data.setDatapartType(dp.getDataPartType());
            data.setFilename(dp.getFileName());
            if (dp.getContentLength() != null && dp.getContentLength() > 0)
                data.setNoOfBytes("" + dp.getContentLength());
            content.getDataOrCompound().add(data);
        }

        bodyPart.setContent(shsLabelMarshaller.marshal(label), "text/xml; charset=ISO-8859-1");
        bodyPart.setHeader("Content-Transfer-Encoding", "binary");

        multipart.addBodyPart(bodyPart);

        for (DataPart dataPart : dataParts) {

            bodyPart = new MimeBodyPart();

            bodyPart.setDisposition(Part.ATTACHMENT);
            if (StringUtils.isNotBlank(dataPart.getFileName())) {
                bodyPart.setFileName(dataPart.getFileName());
            }

            bodyPart.setDataHandler(dataPart.getDataHandler());

            if (dataPart.getTransferEncoding() != null) {
                bodyPart.addHeader("Content-Transfer-Encoding", dataPart.getTransferEncoding().toLowerCase());
            }
            multipart.addBodyPart(bodyPart);
        }

        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setSubject("SHS Message");
        mimeMessage.addHeader("Content-Transfer-Encoding", "binary");

        mimeMessage.setContent(multipart);
        mimeMessage.saveChanges();

        String ignoreList[] = { "Message-ID" };

        mimeMessage.writeTo(outputStream, ignoreList);
        outputStream.flush();

    } catch (Exception e) {
        if (e instanceof IllegalMessageStructureException) {
            throw (IllegalMessageStructureException) e;
        }
        throw new IllegalMessageStructureException(e);
    }

}

From source file:com.zimbra.cs.mailclient.smtp.SmtpConnection.java

private void sendInternal(String sender, String[] recipients, MimeMessage javaMailMessage, String messageString)
        throws IOException, MessagingException {

    invalidRecipients.clear();//from  www  .ja va 2  s  .  co  m
    validRecipients.clear();
    Collections.addAll(validRecipients, recipients);

    mail(sender);

    String notify = null;
    if (serverExtensions.contains("DSN")) {
        if (javaMailMessage instanceof SMTPMessage)
            notify = getDSNNotify((SMTPMessage) javaMailMessage);
        if (notify == null)
            notify = getSmtpConfig().getDsn();
    }

    rcpt(recipients, notify);
    Reply reply = sendCommand(DATA, null);
    if (reply.code != 354) {
        throw new CommandFailedException(DATA, reply.toString());
    }

    SmtpDataOutputStream smtpData = new SmtpDataOutputStream(mailOut);
    try {
        if (javaMailMessage != null) {
            javaMailMessage.writeTo(smtpData, IGNORE_HEADERS);
        } else {
            smtpData.write(messageString.getBytes());
        }
    } catch (MessagingException e) { // close without QUIT
        close();
        throw e;
    } catch (IOException e) { // close without QUIT
        close();
        throw e;
    }
    smtpData.end();
    mailOut.flush();
    mailOut.trace();
    reply = Reply.parse(mailIn.readLine());
    mailIn.trace();
    if (reply == null) {
        throw new CommandFailedException(DATA, "No response");
    }
    if (!reply.isPositive()) {
        throw new CommandFailedException(DATA, reply.toString());
    }
}

From source file:de.mendelson.comm.as2.message.AS2MessageCreation.java

/**Enwrapps the data into a signed MIME message structure and returns it*/
private void enwrappInMessageAndSign(AS2Message message, Part contentPart, Partner sender, Partner receiver)
        throws Exception {
    AS2MessageInfo info = (AS2MessageInfo) message.getAS2Info();
    MimeMessage messagePart = new MimeMessage(Session.getInstance(System.getProperties(), null));
    //sign message if this is requested
    if (info.getSignType() != AS2Message.SIGNATURE_NONE) {
        MimeMultipart signedPart = this.signContentPart(contentPart, sender, receiver);
        if (this.logger != null) {
            String signAlias = this.signatureCertManager.getAliasByFingerprint(sender.getSignFingerprintSHA1());
            this.logger.log(Level.INFO,
                    this.rb.getResourceString("message.signed",
                            new Object[] { info.getMessageId(), signAlias,
                                    this.rbMessage.getResourceString("signature." + receiver.getSignType()) }),
                    info);/*from w ww  .j a  v  a 2  s.c om*/
        }
        messagePart.setContent(signedPart);
        messagePart.saveChanges();
    } else {
        //unsigned message
        if (contentPart instanceof MimeBodyPart) {
            MimeMultipart unsignedPart = new MimeMultipart();
            unsignedPart.addBodyPart((MimeBodyPart) contentPart);
            if (this.logger != null) {
                this.logger.log(Level.INFO,
                        this.rb.getResourceString("message.notsigned", new Object[] { info.getMessageId() }),
                        info);
            }
            messagePart.setContent(unsignedPart);
        } else if (contentPart instanceof MimeMultipart) {
            messagePart.setContent((MimeMultipart) contentPart);
        } else if (contentPart instanceof MimeMessage) {
            messagePart = (MimeMessage) contentPart;
        } else {
            throw new IllegalArgumentException("enwrappInMessageAndSign: Unable to set the content of a "
                    + contentPart.getClass().getName());
        }
        messagePart.saveChanges();
    }
    //store signed or unsigned data
    ByteArrayOutputStream signedOut = new ByteArrayOutputStream();
    //normally the content type header is folded (which is correct but some products are not able to parse this properly)
    //Now take the content-type, unfold it and write it
    Enumeration headerLines = messagePart.getMatchingHeaderLines(new String[] { "Content-Type" });
    LineOutputStream los = new LineOutputStream(signedOut);
    while (headerLines.hasMoreElements()) {
        //requires java mail API >= 1.4
        String nextHeaderLine = MimeUtility.unfold((String) headerLines.nextElement());
        //write the line only if the as2 message is encrypted. If the as2 message is unencrypted this header is added later
        //in the class MessageHttpUploader
        if (info.getEncryptionType() != AS2Message.ENCRYPTION_NONE) {
            los.writeln(nextHeaderLine);
        }
        //store the content line in the as2 message object, this value is required later in MessageHttpUploader
        message.setContentType(nextHeaderLine.substring(nextHeaderLine.indexOf(':') + 1));
    }
    messagePart.writeTo(signedOut, new String[] { "Message-ID", "Mime-Version", "Content-Type" });
    signedOut.flush();
    signedOut.close();
    message.setDecryptedRawData(signedOut.toByteArray());
}