Search in sources :

Example 36 with Multipart

use of javax.mail.Multipart in project mailim by zengsn.

the class EmaiRecever method getAllMultipart.

/**
 * 解析综合数据
 * @param part
 * @throws Exception
 */
public static String getAllMultipart(int j, Part part, boolean isDownload) throws Exception {
    String contentType = part.getContentType();
    Log.e("消息类型:", part.getContentType());
    int index = contentType.indexOf("name");
    boolean conName = false;
    if (index != -1) {
        conName = true;
        Log.e("name", "true");
    }
    String text = "";
    // 判断part类型
    if (part.isMimeType("text/plain") && !conName) {
        text = (String) part.getContent();
    } else if (part.isMimeType("text/html") && !conName) {
        text = (String) part.getContent();
    } else if (part.isMimeType("multipart/*")) {
        Multipart multipart = (Multipart) part.getContent();
        int counts = multipart.getCount();
        for (int i = 0; i < counts; i++) {
            // 递归获取数据
            Log.e("消息数:", String.valueOf(i));
            text += getAllMultipart(j + 1, multipart.getBodyPart(i), isDownload);
            // 附件可能是截图或上传的(图片或其他数据)
            if (isDownload && multipart.getBodyPart(i).getDisposition() != null) {
                // 附件为截图
                if (multipart.getBodyPart(i).isMimeType("image/*")) {
                    InputStream is = multipart.getBodyPart(i).getInputStream();
                    String name = multipart.getBodyPart(i).getFileName();
                    String fileName;
                    // 截图图片
                    if (name.startsWith("=?")) {
                        fileName = name.substring(name.lastIndexOf(".") - 1, name.lastIndexOf("?="));
                    } else {
                        // 上传图片
                        fileName = name;
                    }
                    String time = MailMessageUtil.findValue(text, "时间");
                    FileOutputStream fos = new FileOutputStream(MainActivity.app.getDownlaodFile(time));
                    int len = 0;
                    byte[] bys = new byte[1024];
                    while ((len = is.read(bys)) != -1) {
                        fos.write(bys, 0, len);
                    }
                    fos.close();
                    if (isCidImgAndReplace(text)) {
                        String cid = getCid(multipart.getBodyPart(i));
                        if (cid != null)
                            Log.e("cid:", cid);
                        File file = MainActivity.app.getDownlaodFile(time);
                        fileName = file.getAbsolutePath();
                        Log.e("filename:", fileName);
                        text = replaceLocalPathByImgCid(text, cid, fileName);
                        Log.e("替换后内容:", text);
                    }
                } else {
                    // 其他附件
                    InputStream is = multipart.getBodyPart(i).getInputStream();
                    String name = multipart.getBodyPart(i).getFileName();
                    FileOutputStream fos = new FileOutputStream(MainActivity.app.getDownlaodFile(name));
                    int len = 0;
                    byte[] bys = new byte[1024];
                    while ((len = is.read(bys)) != -1) {
                        fos.write(bys, 0, len);
                    }
                    fos.close();
                }
            }
        }
    } else if (part.isMimeType("message/rfc822")) {
        text = getAllMultipart(j + 1, (Part) part.getContent(), isDownload);
    } else {
    // text = getAllMultipart((Part) part.getContent(),isDownload);
    }
    // Log.e("text内容:",text);
    return text;
}
Also used : Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) InputStream(java.io.InputStream) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 37 with Multipart

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

the class TestSendIcalMessage method sendIcalMessage.

private void sendIcalMessage() throws Exception {
    log.debug("sendIcalMessage");
    // Building MimeMessage
    MimeMessage mimeMessage = mailHandler.getBasicMimeMessage();
    mimeMessage.setSubject(subject);
    mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients, false));
    // -- Create a new message --
    BodyPart msg = new MimeBodyPart();
    msg.setDataHandler(new DataHandler(new ByteArrayDataSource(htmlBody, "text/html; charset=\"utf-8\"")));
    Multipart multipart = new MimeMultipart();
    BodyPart iCalAttachment = new MimeBodyPart();
    iCalAttachment.setDataHandler(new DataHandler(new javax.mail.util.ByteArrayDataSource(new ByteArrayInputStream(iCalMimeBody), "text/calendar;method=REQUEST;charset=\"UTF-8\"")));
    iCalAttachment.setFileName("invite.ics");
    multipart.addBodyPart(iCalAttachment);
    multipart.addBodyPart(msg);
    mimeMessage.setSentDate(new Date());
    mimeMessage.setContent(multipart);
    // -- Set some other header information --
    // mimeMessage.setHeader("X-Mailer", "XML-Mail");
    // mimeMessage.setSentDate(new Date());
    // Transport trans = session.getTransport("smtp");
    Transport.send(mimeMessage);
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) ByteArrayInputStream(java.io.ByteArrayInputStream) DataHandler(javax.activation.DataHandler) MimeBodyPart(javax.mail.internet.MimeBodyPart) ByteArrayDataSource(org.apache.openmeetings.util.mail.ByteArrayDataSource) Date(java.util.Date)

Example 38 with Multipart

use of javax.mail.Multipart in project alliance by codice.

the class EmailSenderImpl method sendEmail.

/**
 * sendEmail method sends email after receiving input parameters
 */
@Override
public void sendEmail(String fromEmail, String toEmail, String subject, String body, List<Pair<String, InputStream>> attachments) throws IOException {
    notNull(fromEmail, "fromEmail must be non-null");
    notNull(toEmail, "toEmail must be non-null");
    notNull(subject, "subject must be non-null");
    notNull(body, "body must be non-null");
    notNull(attachments, "attachments must be non-null");
    if (StringUtils.isBlank(mailHost)) {
        throw new IOException("the mail server hostname has not been configured");
    }
    List<File> tempFiles = new LinkedList<>();
    try {
        InternetAddress emailAddr = new InternetAddress(toEmail);
        emailAddr.validate();
        Properties properties = createSessionProperties();
        Session session = Session.getDefaultInstance(properties);
        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom(new InternetAddress(fromEmail));
        mimeMessage.addRecipient(Message.RecipientType.TO, emailAddr);
        mimeMessage.setSubject(subject);
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(body);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        Holder<Long> bytesWritten = new Holder<>(0L);
        for (Pair<String, InputStream> attachment : attachments) {
            messageBodyPart = new MimeBodyPart();
            File file = File.createTempFile("email-sender-", ".dat");
            tempFiles.add(file);
            copyDataToTempFile(file, attachment.getValue(), bytesWritten);
            messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(file)));
            messageBodyPart.setFileName(attachment.getKey());
            multipart.addBodyPart(messageBodyPart);
        }
        mimeMessage.setContent(multipart);
        send(mimeMessage);
        LOGGER.debug("Email sent to " + toEmail);
    } catch (AddressException e) {
        throw new IOException("invalid email address: email=" + toEmail, e);
    } catch (MessagingException e) {
        throw new IOException("message error occurred on send", e);
    } finally {
        tempFiles.forEach(file -> {
            if (!file.delete()) {
                LOGGER.debug("unable to delete tmp file: path={}", file);
            }
        });
    }
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) InternetAddress(javax.mail.internet.InternetAddress) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) MessagingException(javax.mail.MessagingException) InputStream(java.io.InputStream) Holder(javax.xml.ws.Holder) IOException(java.io.IOException) DataHandler(javax.activation.DataHandler) Properties(java.util.Properties) LinkedList(java.util.LinkedList) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) AddressException(javax.mail.internet.AddressException) FileDataSource(javax.activation.FileDataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File) Session(javax.mail.Session)

Example 39 with Multipart

use of javax.mail.Multipart in project ofbiz-framework by apache.

the class MimeMessageWrapper method setMessage.

public synchronized void setMessage(MimeMessage message) {
    if (message != null) {
        // serialize the message
        this.message = message;
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            message.writeTo(baos);
            baos.flush();
            serializedBytes = baos.toByteArray();
            this.contentType = message.getContentType();
            // see if this is a multi-part message
            Object content = message.getContent();
            if (content instanceof Multipart) {
                Multipart mp = (Multipart) content;
                this.parts = mp.getCount();
            } else {
                this.parts = 0;
            }
        } catch (IOException | MessagingException e) {
            Debug.logError(e, module);
        }
    }
}
Also used : Multipart(javax.mail.Multipart) MessagingException(javax.mail.MessagingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException)

Example 40 with Multipart

use of javax.mail.Multipart in project spring-integration by spring-projects.

the class MailSendingMessageHandlerContextTests method byteArrayMessage.

@Test
public void byteArrayMessage() throws Exception {
    byte[] payload = { 1, 2, 3 };
    org.springframework.messaging.Message<?> message = MessageBuilder.withPayload(payload).setHeader(MailHeaders.ATTACHMENT_FILENAME, "attachment.txt").setHeader(MailHeaders.TO, MailTestsHelper.TO).build();
    this.handler.handleMessage(message);
    assertEquals("no mime message should have been sent", 1, this.mailSender.getSentMimeMessages().size());
    assertEquals("only one simple message must be sent", 0, this.mailSender.getSentSimpleMailMessages().size());
    byte[] buffer = new byte[1024];
    MimeMessage mimeMessage = this.mailSender.getSentMimeMessages().get(0);
    assertTrue("message must be multipart", mimeMessage.getContent() instanceof Multipart);
    int size = new DataInputStream(((Multipart) mimeMessage.getContent()).getBodyPart(0).getInputStream()).read(buffer);
    assertEquals("buffer size does not match", payload.length, size);
    byte[] messageContent = new byte[size];
    System.arraycopy(buffer, 0, messageContent, 0, payload.length);
    assertArrayEquals("buffer content does not match", payload, messageContent);
    assertEquals(mimeMessage.getRecipients(Message.RecipientType.TO).length, MailTestsHelper.TO.length);
}
Also used : Multipart(javax.mail.Multipart) MimeMessage(javax.mail.internet.MimeMessage) DataInputStream(java.io.DataInputStream) Test(org.junit.Test)

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