Example usage for javax.mail.internet MimeMessage MimeMessage

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

Introduction

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

Prototype

protected MimeMessage(Folder folder, int msgnum) 

Source Link

Document

Constructs an empty MimeMessage object with the given Folder and message number.

Usage

From source file:com.zxy.commons.email.MailMessageUtils.java

/**
 * inputStream??/*  w  w w. j ava  2  s.c om*/
 * @param inputStream InputStream
 * @throws EmailException EmailException
 * @throws MessagingException MessagingException
*/
public static void sendEml(InputStream inputStream) throws EmailException, MessagingException {
    try {
        Session session = getEmail().getMailSession();
        MimeMessage message = new MimeMessage(session, inputStream);

        Transport.send(message, message.getAllRecipients());
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:de.contentreich.alfresco.repo.email.EMLTransformer.java

@Override
protected void transformInternal(ContentReader reader, ContentWriter writer, TransformationOptions options)
        throws Exception {
    // TikaInputStream tikaInputStream = null;
    try (InputStream is = reader.getContentInputStream()) {
        // wrap the given stream to a TikaInputStream instance
        // tikaInputStream =  TikaInputStream.get(reader.getContentInputStream());
        // final Icu4jEncodingDetector encodingDetector = new Icu4jEncodingDetector();
        // final Charset charset = encodingDetector.detect(tikaInputStream, new Metadata());

        // MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(new Properties()), tikaInputStream);
        MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(new Properties()), is);
        /*/*from  ww w.j  a  va2s  .com*/
        if (charset != null)
        {
        mimeMessage.setHeader("Content-Type", "text/plain; charset=" + charset.name());
        mimeMessage.setHeader("Content-Transfer-Encoding", "quoted-printable");
        }
        */
        final StringBuilder sb = new StringBuilder();
        Object content = mimeMessage.getContent();
        if (content instanceof Multipart) {
            boolean html = html();
            Map<String, String> parts = new HashMap<String, String>();
            processPreviewMultiPart((Multipart) content, parts);
            String part = getPreview(parts, html);
            if (part != null) {
                sb.append(part);
            }
            // sb.append(processPreviewMultiPart((Multipart) content));
        } else {
            sb.append(content.toString());
        }
        writer.putContent(sb.toString());
    }
    /* finally
    {
    if (tikaInputStream != null)
    {
        try
        {
            // it closes any other resources associated with it
            tikaInputStream.close();
        }
        catch (IOException e)
        {
            logger.error(e.getMessage(), e);
        }
    }
    } */
}

From source file:com.consol.citrus.mail.server.MailServer.java

@Override
public void deliver(String from, String recipient, InputStream data) {
    try {// www .  j  a v  a  2 s . c o m
        MimeMailMessage message = new MimeMailMessage(new MimeMessage(getSession(), data));
        Map<String, String> messageHeaders = createMessageHeaders(message);
        MailMessage mailMessage = createMailMessage(messageHeaders);
        mailMessage.setBody(handlePart(message.getMimeMessage()));

        org.springframework.integration.Message response = invokeMessageHandler(mailMessage, messageHeaders);

        if (response != null && response.getPayload() != null) {
            MailMessageResponse mailResponse = null;
            if (response.getPayload() instanceof MailMessageResponse) {
                mailResponse = (MailMessageResponse) response.getPayload();
            } else if (response.getPayload() instanceof String) {
                mailResponse = (MailMessageResponse) mailMessageMapper
                        .fromXML(response.getPayload().toString());
            }

            if (mailResponse != null && mailResponse.getCode() != MailMessageResponse.OK_CODE) {
                throw new RejectException(mailResponse.getCode(), mailResponse.getMessage());
            }
        }
    } catch (MessagingException e) {
        throw new CitrusRuntimeException(e);
    } catch (IOException e) {
        throw new CitrusRuntimeException(e);
    }
}

From source file:com.cloudhub.gmail.GmailEmailMessageExtractor.java

/**
 * Get a Message and use it to create a MimeMessage.
 *
 * @param messageId ID of Message to retrieve.
 * @return MimeMessage MimeMessage populated from retrieved Message.
 * @throws IOException/*from  w w  w.j a va2 s  . c o m*/
 * @throws MessagingException
 */
public MimeMessage getMimeMessage(String messageId) throws IOException, MessagingException {
    Message message = service.users().messages().get(userId, messageId).setFormat("raw").execute();
    // System.out.println(message.toPrettyString());

    byte[] emailBytes = Base64.decodeBase64(message.getRaw());

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session, new ByteArrayInputStream(emailBytes));

    return email;
}

From source file:com.liferay.util.mail.MailEngine.java

public static void send(byte[] msgByteArray) throws MailEngineException {
    InternetAddress[] from = null;//from  w  ww.  j ava2s . c o  m

    try {
        Session session = getSession();

        Message msg = new MimeMessage(session, new ByteArrayInputStream(msgByteArray));

        from = (InternetAddress[]) msg.getFrom();

        _sendMessage(session, msg);
    } catch (SendFailedException sfe) {
        Logger.error(MailEngine.class, sfe.getMessage(), sfe);
    } catch (Exception e) {
        throw new MailEngineException(e);
    }
}

From source file:com.zotoh.crypto.CryptoUte.java

/**
 * @param inp/*from   w ww  .j a  va  2s .  c o m*/
 * @return
 * @throws MessagingException
 */
public static MimeMessage newMimeMsg(InputStream inp) throws MessagingException {
    tstObjArg("inp-stream", inp);
    return new MimeMessage(newSession(), inp);
}

From source file:mitm.common.mail.MailUtils.java

/**
 * Loads a message from the input stream using the default mail session
 * @param input//from  www . j  av a 2s . c o  m
 * @return
 * @throws MessagingException
 */
public static MimeMessage loadMessage(InputStream input) throws MessagingException {
    MimeMessage message = new MimeMessage(MailSession.getDefaultSession(), input);

    return message;
}

From source file:com.hs.mail.smtp.message.SmtpMessage.java

public MimeMessage getMimeMessage() throws MessagingException {
    Session session = Session.getInstance(System.getProperties(), null);
    InputStream is = null;/*from w  w w.  j a va2 s.c o  m*/
    try {
        is = new FileInputStream(getDataFile());
        return new MimeMessage(session, is);
    } catch (FileNotFoundException e) {
        throw new MessagingException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:gmailclientfx.core.GmailClient.java

public static MimeMessage getMimeMessage(Gmail service, String userId, String messageId)
        throws IOException, MessagingException {
    com.google.api.services.gmail.model.Message message = service.users().messages().get(userId, messageId)
            .setFormat("raw").execute();

    byte[] emailBytes = Base64.decodeBase64(message.getRaw());

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session, new ByteArrayInputStream(emailBytes));

    return email;
}

From source file:de.betterform.connector.smtp.SMTPSubmissionHandler.java

private void send(String uri, byte[] data, String encoding, String mediatype) throws Exception {
    URL url = new URL(uri);
    String recipient = url.getPath();

    String server = null;//from   w w w. j  a v  a2 s .  c  om
    String port = null;
    String sender = null;
    String subject = null;
    String username = null;
    String password = null;

    StringTokenizer headers = new StringTokenizer(url.getQuery(), "&");

    while (headers.hasMoreTokens()) {
        String token = headers.nextToken();

        if (token.startsWith("server=")) {
            server = URLDecoder.decode(token.substring("server=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("port=")) {
            port = URLDecoder.decode(token.substring("port=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("sender=")) {
            sender = URLDecoder.decode(token.substring("sender=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("subject=")) {
            subject = URLDecoder.decode(token.substring("subject=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("username=")) {
            username = URLDecoder.decode(token.substring("username=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("password=")) {
            password = URLDecoder.decode(token.substring("password=".length()), "UTF-8");

            continue;
        }
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("smtp server '" + server + "'");

        if (username != null) {
            LOGGER.debug("smtp-auth username '" + username + "'");
        }

        LOGGER.debug("mail sender '" + sender + "'");
        LOGGER.debug("subject line '" + subject + "'");
    }

    Properties properties = System.getProperties();
    properties.put("mail.debug", String.valueOf(LOGGER.isDebugEnabled()));
    properties.put("mail.smtp.from", sender);
    properties.put("mail.smtp.host", server);

    if (port != null) {
        properties.put("mail.smtp.port", port);
    }

    if (username != null) {
        properties.put("mail.smtp.auth", String.valueOf(true));
        properties.put("mail.smtp.user", username);
    }

    Session session = Session.getInstance(properties, new SMTPAuthenticator(username, password));

    MimeMessage message = null;
    if (mediatype.startsWith("multipart/")) {
        message = new MimeMessage(session, new ByteArrayInputStream(data));
    } else {
        message = new MimeMessage(session);
        if (mediatype.toLowerCase().indexOf("charset=") == -1) {
            mediatype += "; charset=\"" + encoding + "\"";
        }
        message.setText(new String(data, encoding), encoding);
        message.setHeader("Content-Type", mediatype);
    }

    message.setRecipient(RecipientType.TO, new InternetAddress(recipient));
    message.setSubject(subject);
    message.setSentDate(new Date());

    Transport.send(message);
}