Search in sources :

Example 1 with Multipart

use of javax.mail.Multipart in project camel by apache.

the class MailConvertersTest method testMultipartToString.

@Test
public void testMultipartToString() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedMessageCount(1);
    template.send("direct:a", new Processor() {

        public void process(Exchange exchange) throws Exception {
            exchange.getIn().setBody("Hello World");
            exchange.getIn().setHeader(MailConstants.MAIL_ALTERNATIVE_BODY, "Alternative World");
        }
    });
    assertMockEndpointsSatisfied();
    Message mailMessage = mock.getReceivedExchanges().get(0).getIn().getBody(MailMessage.class).getMessage();
    assertNotNull(mailMessage);
    Object content = mailMessage.getContent();
    Multipart mp = assertIsInstanceOf(Multipart.class, content);
    String s = MailConverters.toString(mp);
    assertEquals("Alternative World", s);
}
Also used : Exchange(org.apache.camel.Exchange) Multipart(javax.mail.Multipart) Processor(org.apache.camel.Processor) Message(javax.mail.Message) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) Test(org.junit.Test)

Example 2 with Multipart

use of javax.mail.Multipart in project jodd by oblac.

the class SendMailSession method createMessage.

// ---------------------------------------------------------------- adapter
/**
	 * Creates new JavaX message from {@link Email email}.
	 */
protected MimeMessage createMessage(Email email, Session session) throws MessagingException {
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(email.getFrom().toInternetAddress());
    // to
    int totalTo = email.getTo().length;
    InternetAddress[] address = new InternetAddress[totalTo];
    for (int i = 0; i < totalTo; i++) {
        address[i] = email.getTo()[i].toInternetAddress();
    }
    msg.setRecipients(Message.RecipientType.TO, address);
    // replyTo
    if (email.getReplyTo() != null) {
        int totalReplyTo = email.getReplyTo().length;
        address = new InternetAddress[totalReplyTo];
        for (int i = 0; i < totalReplyTo; i++) {
            address[i] = email.getReplyTo()[i].toInternetAddress();
        }
        msg.setReplyTo(address);
    }
    // cc
    if (email.getCc() != null) {
        int totalCc = email.getCc().length;
        address = new InternetAddress[totalCc];
        for (int i = 0; i < totalCc; i++) {
            address[i] = email.getCc()[i].toInternetAddress();
        }
        msg.setRecipients(Message.RecipientType.CC, address);
    }
    // bcc
    if (email.getBcc() != null) {
        int totalBcc = email.getBcc().length;
        address = new InternetAddress[totalBcc];
        for (int i = 0; i < totalBcc; i++) {
            address[i] = email.getBcc()[i].toInternetAddress();
        }
        msg.setRecipients(Message.RecipientType.BCC, address);
    }
    if (email.getSubjectEncoding() != null) {
        msg.setSubject(email.getSubject(), email.getSubjectEncoding());
    } else {
        msg.setSubject(email.getSubject());
    }
    Date date = email.getSentDate();
    if (date == null) {
        date = new Date();
    }
    msg.setSentDate(date);
    // headers
    Map<String, String> headers = email.getAllHeaders();
    if (headers != null) {
        for (Map.Entry<String, String> stringStringEntry : headers.entrySet()) {
            String value = stringStringEntry.getValue();
            msg.setHeader(stringStringEntry.getKey(), value);
        }
    }
    // message data and attachments
    final List<EmailMessage> messages = email.getAllMessages();
    final List<EmailAttachment> attachments = email.getAttachments() == null ? null : new ArrayList<>(email.getAttachments());
    final int totalMessages = messages.size();
    if ((attachments == null) && (totalMessages == 1)) {
        // special case: no attachments and just one content
        EmailMessage emailMessage = messages.get(0);
        msg.setContent(emailMessage.getContent(), emailMessage.getMimeType() + CHARSET + emailMessage.getEncoding());
    } else {
        Multipart multipart = new MimeMultipart();
        Multipart msgMultipart = multipart;
        if (totalMessages > 1) {
            MimeBodyPart bodyPart = new MimeBodyPart();
            msgMultipart = new MimeMultipart(ALTERNATIVE);
            bodyPart.setContent(msgMultipart);
            multipart.addBodyPart(bodyPart);
        }
        for (EmailMessage emailMessage : messages) {
            // detect embedded attachments
            List<EmailAttachment> embeddedAttachments = filterEmbeddedAttachments(attachments, emailMessage);
            MimeBodyPart bodyPart = new MimeBodyPart();
            if (embeddedAttachments == null) {
                // no embedded attachments, just add message
                bodyPart.setContent(emailMessage.getContent(), emailMessage.getMimeType() + CHARSET + emailMessage.getEncoding());
            } else {
                // embedded attachments detected, join them as related
                MimeMultipart relatedMultipart = new MimeMultipart(RELATED);
                MimeBodyPart messageData = new MimeBodyPart();
                messageData.setContent(emailMessage.getContent(), emailMessage.getMimeType() + CHARSET + emailMessage.getEncoding());
                relatedMultipart.addBodyPart(messageData);
                for (EmailAttachment att : embeddedAttachments) {
                    MimeBodyPart attBodyPart = createAttachmentBodyPart(att);
                    relatedMultipart.addBodyPart(attBodyPart);
                }
                bodyPart.setContent(relatedMultipart);
            }
            msgMultipart.addBodyPart(bodyPart);
        }
        if (attachments != null) {
            // attach remaining attachments
            for (EmailAttachment att : attachments) {
                MimeBodyPart attBodyPart = createAttachmentBodyPart(att);
                multipart.addBodyPart(attBodyPart);
            }
        }
        msg.setContent(multipart);
    }
    return msg;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) Date(java.util.Date) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart) Map(java.util.Map)

Example 3 with Multipart

use of javax.mail.Multipart in project Xponents by OpenSextant.

the class MessageConverter method parseMessage.

/**
     * This is a recursive parser that pulls off attachments into Child content or saves plain text as main message text.
     * Calendar invites are ignored.
     *
     * @param bodyPart  individual sub-part to append to buffer
     * @param parent parent doc
     * @param buf text to append
     * @param msgPrefixId msgId prefix
     * @throws IOException on error
     */
public void parseMessage(Part bodyPart, ConvertedDocument parent, StringBuilder buf, String msgPrefixId) throws IOException {
    InputStream partIO = null;
    ++attachmentNumber;
    try {
        PartMetadata meta = new PartMetadata(bodyPart);
        //String charset = (meta.charset == null ? "UTF-8" : meta.charset);
        textEncodings.add(meta.charset);
        String filename = bodyPart.getFileName();
        String fileext = meta.getPossibleFileExtension();
        if (filename != null) {
            fileext = FilenameUtils.getExtension(filename);
            logger.debug("original filename: " + filename);
        }
        boolean hasExtension = StringUtils.isNotBlank(fileext);
        if (!hasExtension) {
            logger.debug("Unknown message part");
            fileext = "dat";
        }
        if (filename == null && attachmentNumber > 1) {
            filename = String.format("%s-Att%d.%s", msgPrefixId, attachmentNumber, fileext);
        }
        logger.debug("Charset for part is {}", meta.charset);
        // IGNORE types: calendar.
        if (meta.isCalendar()) {
            logger.debug("{}# Ignore item", msgPrefixId);
            return;
        }
        if (meta.isHTML()) {
            //
            logger.debug("{}# Save HTML part as its own file", msgPrefixId);
        } else if (bodyPart.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) bodyPart.getContent();
            int count = mp.getCount();
            for (int i = 0; i < count; i++) {
                // This step does not actually save any content, it calls
                // itself to continue to break down the parts into the
                // finest grained elements, at which point
                parseMessage(mp.getBodyPart(i), parent, buf, msgPrefixId);
            }
            // Exit point
            return;
        } else if (bodyPart.isMimeType("message/rfc822")) {
            /* normal mail message body */
            parseMessage((Part) bodyPart.getContent(), parent, buf, msgPrefixId);
            // Exit point
            return;
        } else {
            Object part = bodyPart.getContent();
            boolean isTextPlain = bodyPart.isMimeType("text/plain");
            if (part instanceof String) {
                /* We will take the first charset encoding found for the body text of hte message.
                     *  If there are HTML views of the data, those individual documents will be child documents with their own encodings.
                     */
                if (meta.charset != null && parent.getEncoding() == null) {
                    parent.setEncoding(meta.charset);
                }
                String text = (String) part;
                if (!isTextPlain) {
                    // Decode TEXT from MIME base64 or QP encoded data.
                    // TODO: Is this necessary? The mime libraries seem to handle base64 unencoding automatically
                    // (at least for text/plain attachments). -jgibson
                    logger.debug("{}# Save String MIME part", msgPrefixId);
                    if (meta.isQP() || meta.isBase64()) {
                        try {
                            partIO = IOUtils.toInputStream(text);
                            byte[] textBytes = decodeMIMEText(partIO, meta.transferEncoding);
                            if (meta.charset != null) {
                                text = new String(textBytes, meta.charset);
                            } else {
                                text = new String(textBytes);
                            }
                        } catch (Exception decodeErr) {
                            logger.error("Decoding error with bare text in body of message");
                        }
                    } else {
                        logger.debug("Other encoding is unaccounted: {}", meta.transferEncoding);
                    }
                }
                if (meta.isAttachment()) {
                    Content child = createBaseChildContent(filename, meta);
                    if (child.encoding == null) {
                        child.encoding = "UTF-8";
                    }
                    child.content = text.getBytes(child.encoding);
                    copyMailAttrs(parent, child);
                    parent.addRawChild(child);
                } else {
                    // Note, before trying any of these decoding trick
                    buf.append(TextUtils.delete_controls(text));
                    buf.append("\n*******************\n");
                // Note, the "=XX" sequence is reserved for RFC822 encoding of special chars and non-ASCII.
                // So I avoid using "=====".... as a separator.
                }
                // Exit point
                return;
            } else if (part instanceof InputStream) {
                // Retrieve byte stream.
                partIO = (InputStream) part;
                Content child = createChildContent(filename, partIO, meta);
                copyMailAttrs(parent, child);
                parent.addRawChild(child);
                // Exit point.
                return;
            } else {
                /* MCU: identify unknown MIME parts */
                logger.debug("Skipping this an unknown bodyPart type: " + part.getClass().getName());
            //return;
            }
        }
        if (bodyPart instanceof MimeBodyPart && !bodyPart.isMimeType("multipart/*")) {
            logger.debug("{}# Saving {} ", msgPrefixId, filename);
            if (meta.disposition == null || meta.isAttachment) {
                partIO = ((MimeBodyPart) bodyPart).getRawInputStream();
                Content child = createChildContent(filename, partIO, meta);
                copyMailAttrs(parent, child);
                if (meta.isHTML() && (meta.isInline() || (!meta.isAttachment()))) {
                    child.meta.setProperty(MAIL_KEY_PREFIX + "html-body", "true");
                }
                parent.addRawChild(child);
                return;
            }
        }
    } catch (MessagingException e2) {
        logger.error("Extraction Failed on Messaging Exception", e2);
    } finally {
        if (partIO != null) {
            partIO.close();
        }
    }
}
Also used : Multipart(javax.mail.Multipart) MessagingException(javax.mail.MessagingException) InputStream(java.io.InputStream) Content(org.opensextant.xtext.Content) MimeBodyPart(javax.mail.internet.MimeBodyPart) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException)

Example 4 with Multipart

use of javax.mail.Multipart in project Axe by DongyuCai.

the class SimpleMailSender method sendHtmlMail.

/**
	 * 以HTML格式发送邮件
	 * 
	 * @param mailInfo
	 *            待发送的邮件信息
	 */
public static boolean sendHtmlMail(MailSenderInfo mailInfo) {
    // 判断是否需要身份认证
    MyAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    // 如果需要身份认证,则创建一个密码验证器
    if (mailInfo.isValidate()) {
        authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
    }
    // 根据邮件会话属性和密码验证器构造一个发送邮件的session
    Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
    try {
        // 根据session创建一个邮件消息
        Message mailMessage = new MimeMessage(sendMailSession);
        // 创建邮件发送者地址
        Address from = new InternetAddress(mailInfo.getFromAddress());
        // 设置邮件消息的发送者
        mailMessage.setFrom(from);
        // 创建邮件的接收者地址,并设置到邮件消息中
        Address to = new InternetAddress(mailInfo.getToAddress());
        // Message.RecipientType.TO属性表示接收者的类型为TO
        mailMessage.setRecipient(Message.RecipientType.TO, to);
        // 设置邮件消息的主题
        mailMessage.setSubject(mailInfo.getSubject());
        // 设置邮件消息发送的时间
        mailMessage.setSentDate(new Date());
        // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
        Multipart mainPart = new MimeMultipart();
        // 创建一个包含HTML内容的MimeBodyPart
        BodyPart html = new MimeBodyPart();
        // 设置HTML内容
        html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        // 将MiniMultipart对象设置为邮件内容
        mailMessage.setContent(mainPart);
        // 发送邮件
        Transport.send(mailMessage);
        return true;
    } catch (MessagingException ex) {
        ex.printStackTrace();
    }
    return false;
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) InternetAddress(javax.mail.internet.InternetAddress) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) MessagingException(javax.mail.MessagingException) Properties(java.util.Properties) Date(java.util.Date) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart) Session(javax.mail.Session)

Example 5 with Multipart

use of javax.mail.Multipart in project jdk8u_jdk by JetBrains.

the class MailTest method sendMail.

void sendMail() {
    try {
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");
        Session session = Session.getInstance(props);
        session.setDebug(true);
        // Define message
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipients(Message.RecipientType.TO, to);
        message.setSubject("this is a multipart test");
        Multipart multipart = new MimeMultipart();
        BodyPart messageBodyPart1 = new MimeBodyPart();
        messageBodyPart1.setText("please send also this Content\n ciao!");
        multipart.addBodyPart(messageBodyPart1);
        BodyPart messageBodyPart2 = new MimeBodyPart();
        messageBodyPart2.setContent("<b>please</b> send also this Content <br>ciao!", "text/html; charset=UTF-8");
        multipart.addBodyPart(messageBodyPart2);
        message.setContent(multipart);
        /*
                Transport tr = session.getTransport("smtp");
                tr.connect(host,user, password);
                tr.sendMessage(message,InternetAddress.parse(to));
                tr.close();
            */
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        message.writeTo(baos);
        String output = baos.toString();
        System.out.println("output = " + output);
        if (output.contains("also this Content")) {
            System.out.println("Test PASSED.");
        } else {
            System.out.println("Test FAILED, missing content.");
            throw new IllegalStateException("Test FAILED, missing content.");
        }
    } catch (MessagingException ignored) {
    } catch (IOException ignored) {
    }
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) InternetAddress(javax.mail.internet.InternetAddress) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) MessagingException(javax.mail.MessagingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Properties(java.util.Properties) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart) Session(javax.mail.Session)

Aggregations

Multipart (javax.mail.Multipart)140 MimeMultipart (javax.mail.internet.MimeMultipart)101 MimeBodyPart (javax.mail.internet.MimeBodyPart)87 MimeMessage (javax.mail.internet.MimeMessage)79 BodyPart (javax.mail.BodyPart)60 InternetAddress (javax.mail.internet.InternetAddress)59 MessagingException (javax.mail.MessagingException)54 Session (javax.mail.Session)42 DataHandler (javax.activation.DataHandler)40 Properties (java.util.Properties)34 IOException (java.io.IOException)33 Date (java.util.Date)29 Message (javax.mail.Message)28 FileDataSource (javax.activation.FileDataSource)26 DataSource (javax.activation.DataSource)23 InputStream (java.io.InputStream)22 File (java.io.File)21 Part (javax.mail.Part)19 Test (org.junit.Test)16 UnsupportedEncodingException (java.io.UnsupportedEncodingException)10