Search in sources :

Example 76 with MimeBodyPart

use of javax.mail.internet.MimeBodyPart in project webservices-axiom by apache.

the class TestCreateSOAPModelBuilderMTOMContentTypeMismatch method runTest.

@Override
protected void runTest() throws Throwable {
    final SOAPSample sample = SOAPSampleSet.NO_HEADER.getMessage(spec);
    // Generate an MTOM message with the wrong content type
    MimeMessage message = new MimeMessage((Session) null);
    MimeMultipart mp = new MimeMultipart("related");
    MimeBodyPart bp = new MimeBodyPart();
    String contentID = "<" + UIDGenerator.generateContentId() + ">";
    bp.setDataHandler(new DataHandler(new DataSource() {

        @Override
        public String getContentType() {
            return "application/xop+xml; charset=\"" + sample.getEncoding() + "\"; type=\"" + spec.getAltSpec().getContentType() + "\"";
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return sample.getInputStream();
        }

        @Override
        public String getName() {
            return null;
        }

        @Override
        public OutputStream getOutputStream() {
            throw new UnsupportedOperationException();
        }
    }));
    bp.addHeader("Content-Transfer-Encoding", "binary");
    bp.addHeader("Content-ID", contentID);
    mp.addBodyPart(bp);
    message.setContent(mp);
    message.saveChanges();
    ContentType contentType = new ContentType(message.getContentType()).toBuilder().setParameter("type", "application/xop+xml").setParameter("start", contentID).setParameter("start-info", spec.getAltSpec().getContentType()).build();
    MemoryBlob blob = Blobs.createMemoryBlob();
    OutputStream out = blob.getOutputStream();
    mp.writeTo(out);
    out.close();
    // Now attempt to create an Axiom builder
    try {
        OMXMLBuilderFactory.createSOAPModelBuilder(metaFactory, MultipartBody.builder().setInputStream(blob.getInputStream()).setContentType(contentType).build());
        fail("Expected SOAPProcessingException");
    } catch (SOAPProcessingException ex) {
    // Expected
    }
}
Also used : ContentType(org.apache.axiom.mime.ContentType) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MemoryBlob(org.apache.axiom.blob.MemoryBlob) OutputStream(java.io.OutputStream) SOAPProcessingException(org.apache.axiom.soap.SOAPProcessingException) DataHandler(javax.activation.DataHandler) SOAPSample(org.apache.axiom.ts.soap.SOAPSample) MimeBodyPart(javax.mail.internet.MimeBodyPart) DataSource(javax.activation.DataSource)

Example 77 with MimeBodyPart

use of javax.mail.internet.MimeBodyPart in project webservices-axiom by apache.

the class AbstractMultipartWriterTest method test.

private void test(String contentTransferEncoding) throws Exception {
    Random random = new Random();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    MultipartWriter mpw = factory.createMultipartWriter(baos, UIDGenerator.generateMimeBoundary());
    byte[] content = new byte[8192];
    random.nextBytes(content);
    OutputStream partOutputStream = mpw.writePart("application/octet-stream", contentTransferEncoding, UIDGenerator.generateContentId());
    partOutputStream.write(content);
    partOutputStream.close();
    mpw.complete();
    MimeMultipart mp = new MimeMultipart(new ByteArrayDataSource(baos.toByteArray()));
    assertEquals(1, mp.getCount());
    MimeBodyPart bp = (MimeBodyPart) mp.getBodyPart(0);
    assertEquals(contentTransferEncoding, bp.getHeader("Content-Transfer-Encoding")[0]);
    baos.reset();
    bp.getDataHandler().writeTo(baos);
    assertTrue(Arrays.equals(content, baos.toByteArray()));
}
Also used : Random(java.util.Random) MimeMultipart(javax.mail.internet.MimeMultipart) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MimeBodyPart(javax.mail.internet.MimeBodyPart) ByteArrayDataSource(org.apache.axiom.attachments.ByteArrayDataSource)

Example 78 with MimeBodyPart

use of javax.mail.internet.MimeBodyPart in project Gargoyle by callakrsos.

the class EmailAttachmentSender method sendEmailWithAttachments.

public static void sendEmailWithAttachments(String host, String port, final String userName, final String password, String toAddress, String subject, String message, String[] attachFiles) throws AddressException, MessagingException {
    // sets SMTP server properties
    Properties properties = new Properties();
    properties.put("mail.smtp.host", host);
    properties.put("mail.smtp.port", port);
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.user", userName);
    properties.put("mail.password", password);
    // creates a new session with an authenticator
    Authenticator auth = new Authenticator() {

        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
        }
    };
    Session session = Session.getInstance(properties, auth);
    // creates a new e-mail message
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(userName));
    InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
    msg.setRecipients(Message.RecipientType.TO, toAddresses);
    msg.setSubject(subject);
    msg.setSentDate(new Date());
    // creates message part
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(message, "text/html");
    // creates multi-part
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);
    // adds attachments
    if (attachFiles != null && attachFiles.length > 0) {
        for (String filePath : attachFiles) {
            MimeBodyPart attachPart = new MimeBodyPart();
            try {
                attachPart.attachFile(filePath);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            multipart.addBodyPart(attachPart);
        }
    }
    // sets the multi-part as e-mail's content
    msg.setContent(multipart);
    // sends the e-mail
    Transport.send(msg);
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) IOException(java.io.IOException) Properties(java.util.Properties) Date(java.util.Date) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart) Authenticator(javax.mail.Authenticator) PasswordAuthentication(javax.mail.PasswordAuthentication) Session(javax.mail.Session)

Example 79 with MimeBodyPart

use of javax.mail.internet.MimeBodyPart in project ddf by codice.

the class SmtpClientImplITCase method testSend.

@Test
public void testSend() throws IOException, MessagingException, ExecutionException, InterruptedException {
    int port = findAvailablePort();
    SimpleSmtpServer server = SimpleSmtpServer.start(port);
    SmtpClientImpl emailService = new SmtpClientImpl();
    emailService.setHostName(HOSTNAME);
    emailService.setPortNumber(port);
    Session session = emailService.createSession();
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setFrom(new InternetAddress(FROM_ADDR));
    mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_ADDR));
    mimeMessage.setSubject(SUBJECT);
    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setText(BODY);
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);
    mimeMessage.setContent(multipart);
    emailService.send(mimeMessage).get();
    server.stop();
    assertThat(server.getReceivedEmailSize(), is(1));
    Iterator emailIterator = server.getReceivedEmail();
    SmtpMessage email = (SmtpMessage) emailIterator.next();
    assertThat(email.getHeaderValue(SUBJECT_HEADER), is(SUBJECT));
    assertThat(email.getHeaderValue(FROM_HEADER), containsString(FROM_ADDR));
    assertThat(email.getHeaderValue(TO_HEADER), containsString(TO_ADDR));
    assertThat(email.getBody(), containsString(BODY));
}
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) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) SmtpMessage(com.dumbster.smtp.SmtpMessage) SimpleSmtpServer(com.dumbster.smtp.SimpleSmtpServer) Iterator(java.util.Iterator) MimeBodyPart(javax.mail.internet.MimeBodyPart) Session(javax.mail.Session) Test(org.junit.Test)

Example 80 with MimeBodyPart

use of javax.mail.internet.MimeBodyPart in project gitblit by gitblit.

the class MailService method createMessage.

/**
	 * Create a message.
	 *
	 * @param mailing
	 * @return a message
	 */
public Message createMessage(Mailing mailing) {
    if (mailing.subject == null) {
        mailing.subject = "";
    }
    if (mailing.content == null) {
        mailing.content = "";
    }
    Message message = new MailMessageImpl(session, mailing.id);
    try {
        String fromAddress = settings.getString(Keys.mail.fromAddress, null);
        if (StringUtils.isEmpty(fromAddress)) {
            fromAddress = "gitblit@gitblit.com";
        }
        InternetAddress from = new InternetAddress(fromAddress, mailing.from == null ? "Gitblit" : mailing.from);
        message.setFrom(from);
        Pattern validEmail = Pattern.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
        // validate & add TO recipients
        List<InternetAddress> to = new ArrayList<InternetAddress>();
        for (String address : mailing.toAddresses) {
            if (StringUtils.isEmpty(address)) {
                continue;
            }
            if (validEmail.matcher(address).find()) {
                try {
                    to.add(new InternetAddress(address));
                } catch (Throwable t) {
                }
            }
        }
        // validate & add CC recipients
        List<InternetAddress> cc = new ArrayList<InternetAddress>();
        for (String address : mailing.ccAddresses) {
            if (StringUtils.isEmpty(address)) {
                continue;
            }
            if (validEmail.matcher(address).find()) {
                try {
                    cc.add(new InternetAddress(address));
                } catch (Throwable t) {
                }
            }
        }
        if (settings.getBoolean(Keys.web.showEmailAddresses, true)) {
            // full disclosure of recipients
            if (to.size() > 0) {
                message.setRecipients(Message.RecipientType.TO, to.toArray(new InternetAddress[to.size()]));
            }
            if (cc.size() > 0) {
                message.setRecipients(Message.RecipientType.CC, cc.toArray(new InternetAddress[cc.size()]));
            }
        } else {
            // everyone is bcc'd
            List<InternetAddress> bcc = new ArrayList<InternetAddress>();
            bcc.addAll(to);
            bcc.addAll(cc);
            message.setRecipients(Message.RecipientType.BCC, bcc.toArray(new InternetAddress[bcc.size()]));
        }
        message.setSentDate(new Date());
        // UTF-8 encode
        message.setSubject(MimeUtility.encodeText(mailing.subject, "utf-8", "B"));
        MimeBodyPart messagePart = new MimeBodyPart();
        messagePart.setText(mailing.content, "utf-8");
        if (Mailing.Type.html == mailing.type) {
            messagePart.setHeader("Content-Type", "text/html; charset=\"utf-8\"");
        } else {
            messagePart.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
        }
        MimeMultipart multiPart = new MimeMultipart();
        multiPart.addBodyPart(messagePart);
        // handle attachments
        if (mailing.hasAttachments()) {
            for (File file : mailing.attachments) {
                if (file.exists()) {
                    MimeBodyPart filePart = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(file);
                    filePart.setDataHandler(new DataHandler(fds));
                    filePart.setFileName(fds.getName());
                    multiPart.addBodyPart(filePart);
                }
            }
        }
        message.setContent(multiPart);
    } catch (Exception e) {
        logger.error("Failed to properly create message", e);
    }
    return message;
}
Also used : Pattern(java.util.regex.Pattern) InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) ArrayList(java.util.ArrayList) DataHandler(javax.activation.DataHandler) Date(java.util.Date) MessagingException(javax.mail.MessagingException) SendFailedException(javax.mail.SendFailedException) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File)

Aggregations

MimeBodyPart (javax.mail.internet.MimeBodyPart)172 MimeMultipart (javax.mail.internet.MimeMultipart)111 MimeMessage (javax.mail.internet.MimeMessage)65 MessagingException (javax.mail.MessagingException)64 IOException (java.io.IOException)49 DataHandler (javax.activation.DataHandler)39 ByteString (com.linkedin.data.ByteString)38 ByteArrayOutputStream (java.io.ByteArrayOutputStream)37 BodyPart (javax.mail.BodyPart)35 InternetAddress (javax.mail.internet.InternetAddress)31 ZMimeBodyPart (com.zimbra.common.zmime.ZMimeBodyPart)30 Test (org.testng.annotations.Test)28 ZMimeMultipart (com.zimbra.common.zmime.ZMimeMultipart)23 Multipart (javax.mail.Multipart)20 InputStream (java.io.InputStream)18 ArrayList (java.util.ArrayList)17 HashMap (java.util.HashMap)16 Session (javax.mail.Session)16 Date (java.util.Date)15 Properties (java.util.Properties)15