Example usage for javax.mail Message writeTo

List of usage examples for javax.mail Message writeTo

Introduction

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

Prototype

public void writeTo(OutputStream os) throws IOException, MessagingException;

Source Link

Document

Output a bytestream for this Part.

Usage

From source file:org.xwiki.contrib.mail.internal.DefaultMailReader.java

/**
 * {@inheritDoc}/* w w w .  j  av a2  s  .  co  m*/
 * 
 * @see org.xwiki.contrib.mail.IMailReader#cloneEmail(javax.mail.Message, java.lang.String, java.lang.String)
 */
public MimeMessage cloneEmail(final Message mail) {
    MimeMessage cmail = null;
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        mail.writeTo(bos);
        bos.close();
        SharedByteArrayInputStream bis = new SharedByteArrayInputStream(bos.toByteArray());

        cmail = new MimeMessage(this.session, bis);
        bis.close();
    } catch (Exception e) {
        logger.warn("Could not clone email", e);
        return null;
    }

    return cmail;
}

From source file:org.apache.nifi.processors.email.ConsumeEWS.java

/**
 * Disposes the message by converting it to a {@link FlowFile} transferring
 * it to the REL_SUCCESS relationship./*from w ww  .  j  av  a2s .  c om*/
 */
private void transfer(Message emailMessage, ProcessContext context, ProcessSession processSession) {
    long start = System.nanoTime();
    FlowFile flowFile = processSession.create();

    flowFile = processSession.append(flowFile, new OutputStreamCallback() {
        @Override
        public void process(final OutputStream out) throws IOException {
            try {
                emailMessage.writeTo(out);
            } catch (MessagingException e) {
                throw new IOException(e);
            }
        }
    });

    long executionDuration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);

    String fromAddressesString = "";
    try {
        Address[] fromAddresses = emailMessage.getFrom();
        if (fromAddresses != null) {
            fromAddressesString = Arrays.asList(fromAddresses).toString();
        }
    } catch (MessagingException e) {
        this.logger.warn("Faild to retrieve 'From' attribute from Message.");
    }

    processSession.getProvenanceReporter().receive(flowFile, this.displayUrl,
            "Received message from " + fromAddressesString, executionDuration);
    this.getLogger().info("Successfully received {} from {} in {} millis",
            new Object[] { flowFile, fromAddressesString, executionDuration });
    processSession.transfer(flowFile, REL_SUCCESS);

    try {
        emailMessage.setFlag(Flags.Flag.DELETED, this.shouldSetDeleteFlag);
    } catch (MessagingException e) {
        this.logger.warn("Failed to set DELETE Flag on the message, data duplication may occur.");
    }
}

From source file:ste.xtest.mail.FileTransport.java

@Override
public void sendMessage(Message message, Address[] addresses) throws MessagingException {
    String path = getProperty(MAIL_FILE_PATH);

    protocolConnect(null, -1, (auth != null) ? auth.getUserName() : null,
            (auth != null) ? auth.getPassword() : null);

    ////from   ww  w . j a va2  s  .  c o m
    // if path is still missing, let's give up
    //
    if (StringUtils.isEmpty(path)) {
        throw new MessagingException(String.format(
                "missing message path; make sure %s is set in either the session or System properties",
                MAIL_FILE_PATH));
    }

    //
    // We append multiple messages to the same output file
    //
    try (FileOutputStream out = new FileOutputStream(path, true)) {
        message.writeTo(out);
    } catch (IOException x) {
        throw new MessagingException(
                String.format("failed to write %s: %s", path, x.getMessage().toLowerCase()), x);
    }
}

From source file:mail.MailService.java

/**
 * Erstellt eine MIME-Mail.//from   w  w  w  .  j a v  a 2 s. c o  m
 * @param email
 * @throws MessagingException
 * @throws IOException
 */
public String createMail1(Mail email, Config config) throws MessagingException, IOException {

    Properties props = new Properties();
    props.put("mail.smtp.host", "mail.java-tutor.com");
    Session session = Session.getDefaultInstance(props);

    Message msg = new MimeMessage(session);
    //      msg.setHeader("MIME-Version" , "1.0"); 
    //      msg.setHeader("Content-Type" , "text/plain"); 

    // Absender
    InternetAddress addressFrom = new InternetAddress(email.getAbsender());
    msg.setFrom(addressFrom);

    // Empfnger
    InternetAddress addressTo = new InternetAddress(email.getEmpfaenger());
    msg.setRecipient(Message.RecipientType.TO, addressTo);

    msg.setSubject(email.getBetreff());
    msg.setSentDate(email.getAbsendeDatum());
    String txt = Utils.toString(email.getText());

    msg.setText(txt);
    msg.saveChanges();

    // Mail in Ausgabestrom schreiben
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    try {
        msg.writeTo(bOut);
    } catch (IOException e) {
        if (config.isTest())
            System.out.println("Fehler beim Schreiben der Mail in Schritt 1");
        throw e;
    }
    return removeMessageId(bOut.toString(Charset.defaultCharset().name()));
}

From source file:org.xwiki.contrib.mailarchive.internal.DefaultMailArchive.java

@Override
public void dumpEmail(final Message message) {
    try {//from ww  w.  jav  a2  s .com
        final String id = JavamailMessageParser.extractSingleHeader(message, "Message-ID")
                .replaceAll("[^a-zA-Z0-9-_\\.]", "_");
        final File emlFile = new File(environment.getPermanentDirectory(), "mailarchive/dump/" + id + ".eml");

        emlFile.createNewFile();

        final FileOutputStream fo = new FileOutputStream(emlFile);
        message.writeTo(fo);
        fo.flush();
        fo.close();

        logger.debug("Message dumped into {}.eml", id);
    } catch (Throwable t) {
        // we catch Throwable because we don't want to cause problems in debug mode
        logger.debug("Could not dump message for debug", t);
    }
}

From source file:org.apache.jmeter.protocol.mail.sampler.MailReaderSampler.java

/**
 * {@inheritDoc}/*from  w ww. j a  v  a  2  s .co  m*/
 */
@Override
public SampleResult sample(Entry e) {
    SampleResult parent = new SampleResult();
    boolean isOK = false; // Did sample succeed?
    final boolean deleteMessages = getDeleteMessages();
    final String serverProtocol = getServerType();

    parent.setSampleLabel(getName());

    String samplerString = toString();
    parent.setSamplerData(samplerString);

    /*
     * Perform the sampling
     */
    parent.sampleStart(); // Start timing
    try {
        // Create empty properties
        Properties props = new Properties();

        if (isUseStartTLS()) {
            props.setProperty(mailProp(serverProtocol, "starttls.enable"), TRUE); // $NON-NLS-1$
            if (isEnforceStartTLS()) {
                // Requires JavaMail 1.4.2+
                props.setProperty(mailProp(serverProtocol, "starttls.require"), TRUE); // $NON-NLS-1$
            }
        }

        if (isTrustAllCerts()) {
            if (isUseSSL()) {
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"),
                        TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            } else if (isUseStartTLS()) {
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"),
                        TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            }
        } else if (isUseLocalTrustStore()) {
            File truststore = new File(getTrustStoreToUse());
            log.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath());
            if (!truststore.exists()) {
                log.info("load local truststore -Failed to load truststore from: "
                        + truststore.getAbsolutePath());
                truststore = new File(FileServer.getFileServer().getBaseDir(), getTrustStoreToUse());
                log.info("load local truststore -Attempting to read truststore from:  "
                        + truststore.getAbsolutePath());
                if (!truststore.exists()) {
                    log.info("load local truststore -Failed to load truststore from: "
                            + truststore.getAbsolutePath()
                            + ". Local truststore not available, aborting execution.");
                    throw new IOException("Local truststore file not found. Also not available under : "
                            + truststore.getAbsolutePath());
                }
            }
            if (isUseSSL()) {
                // Requires JavaMail 1.4.2+
                props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$ 
                        new LocalTrustStoreSSLSocketFactory(truststore));
                props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            } else if (isUseStartTLS()) {
                // Requires JavaMail 1.4.2+
                props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$
                        new LocalTrustStoreSSLSocketFactory(truststore));
                props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            }
        }

        // Get session
        Session session = Session.getInstance(props, null);

        // Get the store
        Store store = session.getStore(serverProtocol);
        store.connect(getServer(), getPortAsInt(), getUserName(), getPassword());

        // Get folder
        Folder folder = store.getFolder(getFolder());
        if (deleteMessages) {
            folder.open(Folder.READ_WRITE);
        } else {
            folder.open(Folder.READ_ONLY);
        }

        final int messageTotal = folder.getMessageCount();
        int n = getNumMessages();
        if (n == ALL_MESSAGES || n > messageTotal) {
            n = messageTotal;
        }

        // Get directory
        Message[] messages = folder.getMessages(1, n);
        StringBuilder pdata = new StringBuilder();
        pdata.append(messages.length);
        pdata.append(" messages found\n");
        parent.setResponseData(pdata.toString(), null);
        parent.setDataType(SampleResult.TEXT);
        parent.setContentType("text/plain"); // $NON-NLS-1$

        final boolean headerOnly = getHeaderOnly();
        busy = true;
        for (Message message : messages) {
            StringBuilder cdata = new StringBuilder();
            SampleResult child = new SampleResult();
            child.sampleStart();

            cdata.append("Message "); // $NON-NLS-1$
            cdata.append(message.getMessageNumber());
            child.setSampleLabel(cdata.toString());
            child.setSamplerData(cdata.toString());
            cdata.setLength(0);

            final String contentType = message.getContentType();
            child.setContentType(contentType);// Store the content-type
            child.setDataEncoding(RFC_822_DEFAULT_ENCODING); // RFC 822 uses ascii per default
            child.setEncodingAndType(contentType);// Parse the content-type

            if (isStoreMimeMessage()) {
                // Don't save headers - they are already in the raw message
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                message.writeTo(bout);
                child.setResponseData(bout.toByteArray()); // Save raw message
                child.setDataType(SampleResult.TEXT);
            } else {
                @SuppressWarnings("unchecked") // Javadoc for the API says this is OK
                Enumeration<Header> hdrs = message.getAllHeaders();
                while (hdrs.hasMoreElements()) {
                    Header hdr = hdrs.nextElement();
                    String value = hdr.getValue();
                    try {
                        value = MimeUtility.decodeText(value);
                    } catch (UnsupportedEncodingException uce) {
                        // ignored
                    }
                    cdata.append(hdr.getName()).append(": ").append(value).append("\n");
                }
                child.setResponseHeaders(cdata.toString());
                cdata.setLength(0);
                if (!headerOnly) {
                    appendMessageData(child, message);
                }
            }

            if (deleteMessages) {
                message.setFlag(Flags.Flag.DELETED, true);
            }
            child.setResponseOK();
            if (child.getEndTime() == 0) {// Avoid double-call if addSubResult was called.
                child.sampleEnd();
            }
            parent.addSubResult(child);
        }

        // Close connection
        folder.close(true);
        store.close();

        parent.setResponseCodeOK();
        parent.setResponseMessageOK();
        isOK = true;
    } catch (NoClassDefFoundError | IOException ex) {
        log.debug("", ex);// No need to log normally, as we set the status
        parent.setResponseCode("500"); // $NON-NLS-1$
        parent.setResponseMessage(ex.toString());
    } catch (MessagingException ex) {
        log.debug("", ex);// No need to log normally, as we set the status
        parent.setResponseCode("500"); // $NON-NLS-1$
        parent.setResponseMessage(ex.toString() + "\n" + samplerString); // $NON-NLS-1$
    } finally {
        busy = false;
    }

    if (parent.getEndTime() == 0) {// not been set by any child samples
        parent.sampleEnd();
    }
    parent.setSuccessful(isOK);
    return parent;
}

From source file:mail.MailService.java

/**
 * Erstellt eine kanonisierte MIME-Mail.
 * @param email/*ww w. j  a  v a  2  s.c  o  m*/
 * @throws MessagingException
 * @throws IOException
 */
public String createMail2(Mail email, Config config) throws MessagingException, IOException {

    byte[] mailAsBytes = email.getText();
    int laenge = mailAsBytes.length + getCRLF().length;
    byte[] bOout = new byte[laenge];
    for (int i = 0; i < mailAsBytes.length; i++) {
        bOout[i] = mailAsBytes[i];
    }

    byte[] neu = getCRLF();
    int counter = 0;
    for (int i = mailAsBytes.length; i < laenge; i++) {
        bOout[i] = neu[counter];
        counter++;
    }

    email.setText(bOout);

    Properties props = new Properties();
    props.put("mail.smtp.host", "mail.java-tutor.com");
    Session session = Session.getDefaultInstance(props);

    Message msg = new MimeMessage(session);
    //      msg.setHeader("MIME-Version" , "1.0"); 
    //      msg.setHeader("Content-Type" , "text/plain"); 

    // Absender
    InternetAddress addressFrom = new InternetAddress(email.getAbsender());
    msg.setFrom(addressFrom);

    // Empfnger
    InternetAddress addressTo = new InternetAddress(email.getEmpfaenger());
    msg.setRecipient(Message.RecipientType.TO, addressTo);

    msg.setSubject(email.getBetreff());
    msg.setSentDate(email.getAbsendeDatum());

    msg.setText(Utils.toString(email.getText()));
    msg.saveChanges();
    /*       
           // Erstellen des Content
           MimeMultipart content = new MimeMultipart("text"); 
                  
           MimeBodyPart part = new MimeBodyPart(); 
           part.setText(email.getText()); 
           part.setHeader("MIME-Version" , "1.0"); 
           part.setHeader("Content-Type" , part.getContentType()); 
                   
           content.addBodyPart(part);
           System.out.println(content.getContentType());
                  
          Message msg = new MimeMessage(session); 
          msg.setContent(content); 
          msg.setHeader("MIME-Version" , "1.0"); 
          msg.setHeader("Content-Type" , content.getContentType()); 
            
          InternetAddress addressFrom = new InternetAddress(email.getAbsender()); 
           msg.setFrom(addressFrom); 
                   
           InternetAddress addressTo = new InternetAddress(email.getEmpfnger()); 
           msg.setRecipient(Message.RecipientType.TO, addressTo); 
                   
           msg.setSubject(email.getBetreff());
           msg.setSentDate(email.getAbsendeDatum()); */

    //msg.setContent(email.getText(), "text/plain");

    // Mail in Ausgabestrom schreiben
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    try {
        msg.writeTo(bOut);
    } catch (IOException e) {
        System.out.println("Fehler beim Schreiben der Mail in Schritt 2");
        throw e;
    }
    //      String out = bOut.toString();
    //       int pos1 = out.indexOf("Message-ID");
    //       int pos2 = out.indexOf("@localhost") + 13;
    //       String output = out.subSequence(0, pos1).toString();
    //       output += (out.substring(pos2));

    return removeMessageId(bOut.toString(Charset.defaultCharset().name()));
}

From source file:com.warsaw.data.controller.LoginController.java

private Message buildEmail(Session session, String to) throws Exception {
    Message message = new MimeMessage(session);

    message.setFrom(new InternetAddress(EMAIL));

    // Set To: header field of the header.
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

    // Set Subject: header field
    message.setSubject("Testing Subject");

    // This mail has 2 part, the BODY and the embedded image
    MimeMultipart multipart = new MimeMultipart("related");

    // first part (the html)
    BodyPart messageBodyPart = new MimeBodyPart();
    String htmlText = "<img style='width:800px' src=\"cid:image1\"><br/>" + "Dzie dobry,<br/><br/>"
            + "witamy na portalu TrasyPoWarszawsku.pl, na ktrym zostalo "
            + "zaoone konto<br/> dla osoby o danych: Jan Marian Ptak. W celu zakoczenia procesu tworzenia "
            + "konta prosimy uy linku aktywacyjnego:<br/><br/>"
            + "<a href='https://test.puesc.gov.pl?link=Gkhh&%JK.'>https://test.puesc.gov.pl?link=Gkhh&%JK.</a><br/><br/>"
            + "Na wywietlonym ekranie prosz wprowadzi zdefiniowane przez siebie haso awaryjne. Po prawidowym"
            + " wprowadzeniu danych<br/> oraz  ustawieniu nowego  hasa dostpowego  konto  na portalu PUESC zostanie aktywowane.<br/>"
            + "Link aktywacyjny pozostanie wany przez 24 godziny od momentu  otrzymania niniejszej wiadomoci.<br/><br/>"
            + "<img style='width:800px' src=\"cid:image2\"><br/><br/>" + "Z powaaniem<br/><br/>"
            + "Zesp portalu PUESC<br/>" + "puesc@mofnet.gov.pl<br/>"
            + "<a href='http://puesc.gov.pl'>http://puesc.gov.pl</a>";

    messageBodyPart.setContent(htmlText, "text/html; charset=ISO-8859-2");
    // add it//from  ww  w .j a  v a 2 s .  co m
    multipart.addBodyPart(messageBodyPart);

    // second part (the image)
    messageBodyPart = new MimeBodyPart();
    DataSource fds = new FileDataSource("C:\\Users\\Pawel\\Desktop\\header.png");

    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID", "<image1>");

    // add image to the multipart
    multipart.addBodyPart(messageBodyPart);

    messageBodyPart = new MimeBodyPart();
    //  URL url = new URL("http://ns3342351.ovh.net:8080/seap_lf_graphicsLayout_theme/images/refresh.png");
    // URLDataSource fds1 =new URLDataSource(url);
    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID", "<image2>");
    multipart.addBodyPart(messageBodyPart);

    // put everything together
    message.setContent(multipart);

    ByteArrayOutputStream b = new ByteArrayOutputStream();
    try {
        message.writeTo(b);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return message;
}

From source file:org.nuxeo.cm.mail.actionpipe.ExtractMessageInformation.java

@Override
@SuppressWarnings("deprecation")
public boolean execute(ExecutionContext context) throws MessagingException {
    File tmpOutput = null;/*from   w  w  w  . j  a v  a2  s . c o  m*/
    OutputStream out = null;
    try {
        Message originalMessage = context.getMessage();
        if (log.isDebugEnabled()) {
            log.debug("Transforming message, original subject: " + originalMessage.getSubject());
        }

        // fully load the message before trying to parse to
        // override most of server bugs, see
        // http://java.sun.com/products/javamail/FAQ.html#imapserverbug
        Message message;
        if (originalMessage instanceof MimeMessage) {
            message = new MimeMessage((MimeMessage) originalMessage);
            if (log.isDebugEnabled()) {
                log.debug("Transforming message after full load: " + message.getSubject());
            }
        } else {
            // stuck with the original one
            message = originalMessage;
        }

        Address[] from = message.getFrom();
        if (from != null) {
            Address addr = from[0];
            if (addr instanceof InternetAddress) {
                InternetAddress iAddr = (InternetAddress) addr;
                context.put(SENDER_KEY, iAddr.getPersonal());
                context.put(SENDER_EMAIL_KEY, iAddr.getAddress());
            } else {
                context.put(SENDER_KEY, addr.toString());
            }
        }
        Date receivedDate = message.getReceivedDate();
        if (receivedDate == null) {
            // try to get header manually
            String[] dateHeader = message.getHeader("Date");
            if (dateHeader != null) {
                try {
                    long time = Date.parse(dateHeader[0]);
                    receivedDate = new Date(time);
                } catch (IllegalArgumentException e) {
                    // nevermind
                }
            }
        }

        if (receivedDate != null) {
            Calendar date = Calendar.getInstance();
            date.setTime(receivedDate);
            context.put(RECEPTION_DATE_KEY, date);
        }
        String subject = message.getSubject();
        if (subject != null) {
            subject = subject.trim();
        }
        if (subject == null || "".equals(subject)) {
            subject = "<Unknown>";
        }
        context.put(SUBJECT_KEY, subject);
        String[] messageIdHeader = message.getHeader("Message-ID");
        if (messageIdHeader != null) {
            context.put(MESSAGE_ID_KEY, messageIdHeader[0]);
        }

        // TODO: pass it through initial context
        MimetypeRegistry mimeService = (MimetypeRegistry) context.getInitialContext().get(MIMETYPE_SERVICE_KEY);
        if (mimeService == null) {
            log.error("Could not retrieve mimetype service");
        }

        // add all content as first blob
        tmpOutput = File.createTempFile("injectedEmail", ".eml");
        Framework.trackFile(tmpOutput, tmpOutput);
        out = new FileOutputStream(tmpOutput);
        message.writeTo(out);
        Blob blob = Blobs.createBlob(tmpOutput, MESSAGE_RFC822_MIMETYPE, null, subject + ".eml");

        List<Blob> blobs = new ArrayList<>();
        blobs.add(blob);
        context.put(ATTACHMENTS_KEY, blobs);

        // process content
        getAttachmentParts(message, subject, mimeService, context);
        return true;
    } catch (IOException e) {
        log.error(e);
    } finally {
        IOUtils.closeQuietly(out);
    }
    return false;
}

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

public void processAttachFromMessages(HttpServletRequest request, HttpServletResponse response,
        PrintWriter out) {/*  w  w w .  j  a va 2s . c  o  m*/
    try {
        MailAccount account = getAccount(request);
        account.checkStoreConnected();

        String tag = request.getParameter("tag");
        String pfoldername = request.getParameter("folder");
        String suids[] = request.getParameterValues("ids");
        String multifolder = request.getParameter("multifolder");
        boolean mf = multifolder != null && multifolder.equals("true");

        String ctype = "message/rfc822";

        ArrayList<WebTopSession.UploadedFile> ufiles = new ArrayList<>();
        for (String suid : suids) {
            String foldername = pfoldername;

            if (mf) {
                int ix = suid.indexOf("|");
                foldername = suid.substring(0, ix);
                suid = suid.substring(ix + 1);
            }
            long uid = Long.parseLong(suid);
            FolderCache mcache = account.getFolderCache(foldername);

            Message msg = mcache.getMessage(uid);
            File file = WT.createTempFile();
            FileOutputStream fos = new FileOutputStream(file);
            msg.writeTo(fos);
            fos.close();
            long filesize = file.length();
            String filename = msg.getSubject() + ".eml";

            WebTopSession.UploadedFile uploadedFile = new WebTopSession.UploadedFile(false, this.SERVICE_ID,
                    file.getName(), tag, filename, filesize, ctype);
            environment.getSession().addUploadedFile(uploadedFile);
            ufiles.add(uploadedFile);
        }

        MapItemList data = new MapItemList();
        for (WebTopSession.UploadedFile ufile : ufiles) {
            MapItem mi = new MapItem();
            mi.add("uploadId", ufile.getUploadId());
            mi.add("name", ufile.getFilename());
            mi.add("size", ufile.getSize());
            mi.add("editable", isFileEditableInDocEditor(ufile.getFilename()));
            data.add(mi);
        }
        new JsonResult(data).printTo(out);
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
        new JsonResult(false, exc.getMessage()).printTo(out);
    }
}