Search in sources :

Example 71 with MimeBodyPart

use of javax.mail.internet.MimeBodyPart in project SpringStepByStep by JavaProgrammerLB.

the class SendAttachmentInEmail method main.

public static void main(String[] args) {
    // Recipient's email ID needs to be mentioned.
    String to = "destinationemail@gmail.com";
    // Sender's email ID needs to be mentioned
    String from = "fromemail@gmail.com";
    //change accordingly
    final String username = "manishaspatil";
    //change accordingly
    final String password = "******";
    // Assuming you are sending email through relay.jangosmtp.net
    String host = "relay.jangosmtp.net";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", "25");
    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });
    try {
        // Create a default MimeMessage object.
        Message message = new MimeMessage(session);
        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));
        // Set To: header field of the header.
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        // Set Subject: header field
        message.setSubject("Testing Subject");
        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();
        // Now set the actual message
        messageBodyPart.setText("This is message body");
        // Create a multipar message
        Multipart multipart = new MimeMultipart();
        // Set text message part
        multipart.addBodyPart(messageBodyPart);
        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = "/home/manisha/file.txt";
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);
        // Send the complete message parts
        message.setContent(multipart);
        // Send message
        Transport.send(message);
        System.out.println("Sent message successfully....");
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}
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) MessagingException(javax.mail.MessagingException) DataHandler(javax.activation.DataHandler) Properties(java.util.Properties) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) Session(javax.mail.Session) PasswordAuthentication(javax.mail.PasswordAuthentication)

Example 72 with MimeBodyPart

use of javax.mail.internet.MimeBodyPart in project nhin-d by DirectProject.

the class MDNFactory method create.

/**
     * Answers a MimeMultipartReport containing a
     * Message Delivery Notification as specified by RFC 2298.
     * 
     * @param humanText
     * @param reporting_UA_name
     * @param reporting_UA_product
     * @param original_recipient
     * @param final_recipient
     * @param original_message_id
     * @param disposition
     * @return MimeMultipartReport
     * @throws MessagingException
     */
public static MimeMultipartReport create(String humanText, String reporting_UA_name, String reporting_UA_product, String original_recipient, String final_recipient, String original_message_id, String error, MdnGateway gateway, Disposition disposition) throws MessagingException {
    if (disposition == null)
        throw new IllegalArgumentException("Disposition can not be null.");
    // Create the message parts. According to RFC 2298, there are two
    // compulsory parts and one optional part...
    MimeMultipartReport multiPart = new MimeMultipartReport();
    multiPart.setReportType("disposition-notification");
    // Part 1: The 'human-readable' part
    MimeBodyPart humanPart = new MimeBodyPart();
    humanPart.setText(humanText);
    multiPart.addBodyPart(humanPart);
    // Part 2: MDN Report Part
    // 1) reporting-ua-field
    StringBuilder mdnReport = new StringBuilder(128);
    if (reporting_UA_name != null && !reporting_UA_name.isEmpty()) {
        mdnReport.append("Reporting-UA: ");
        mdnReport.append((reporting_UA_name == null ? "" : reporting_UA_name));
        mdnReport.append("; ");
        mdnReport.append((reporting_UA_product == null ? "" : reporting_UA_product));
        mdnReport.append("\r\n");
    }
    // 2) original-recipient-field
    if (original_recipient != null && !original_recipient.isEmpty()) {
        mdnReport.append("Original-Recipient: ");
        mdnReport.append("rfc822; ");
        mdnReport.append(original_recipient);
        mdnReport.append("\r\n");
    }
    // 3) final-recipient-field
    if (final_recipient != null && !final_recipient.isEmpty()) {
        mdnReport.append("Final-Recipient: ");
        mdnReport.append("rfc822; ");
        mdnReport.append(final_recipient);
        mdnReport.append("\r\n");
    }
    // 4) original-message-id-field
    if (original_message_id != null && !original_message_id.isEmpty()) {
        mdnReport.append("Original-Message-ID: ");
        mdnReport.append(original_message_id);
        mdnReport.append("\r\n");
    }
    // 5) mdn-gateway-field
    if (gateway != null) {
        mdnReport.append("MDN-Gateway: ");
        mdnReport.append(gateway.toString());
        mdnReport.append("\r\n");
    }
    // 6) error-field
    if (error != null && !error.isEmpty()) {
        mdnReport.append("Error: ");
        mdnReport.append(error);
        mdnReport.append("\r\n");
    }
    mdnReport.append(disposition.toString());
    mdnReport.append("\r\n");
    MimeBodyPart mdnPart = new MimeBodyPart();
    try {
        // using a DataSource gets around some of the issues with the JAF dynamically loading content handlers that may not work, speicifically
        // the java dsn library and the DispostionNotification class which doesn't know how to handle byte arrays
        ByteArrayDataSource dataSource = new ByteArrayDataSource(new ByteArrayInputStream(mdnReport.toString().getBytes()), "message/disposition-notification");
        mdnPart.setDataHandler(new DataHandler(dataSource));
        multiPart.addBodyPart(mdnPart);
    } catch (IOException e) {
    /*no-op*/
    }
    // described in RFC 1892. It would be a useful addition!        
    return multiPart;
}
Also used : MimeMultipartReport(org.apache.mailet.base.mail.MimeMultipartReport) ByteArrayInputStream(java.io.ByteArrayInputStream) DataHandler(javax.activation.DataHandler) IOException(java.io.IOException) MimeBodyPart(javax.mail.internet.MimeBodyPart) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource)

Example 73 with MimeBodyPart

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

the class MIMEOutputUtils method createMimeBodyPart.

/**
     * @deprecated This method is only useful in conjunction with
     *             {@link #writeBodyPart(OutputStream, MimeBodyPart, String)}, which is deprecated.
     */
public static MimeBodyPart createMimeBodyPart(String contentID, DataHandler dataHandler, OMOutputFormat omOutputFormat) throws MessagingException {
    String contentType = dataHandler.getContentType();
    // Get the content-transfer-encoding
    String contentTransferEncoding = "binary";
    if (dataHandler instanceof ConfigurableDataHandler) {
        ConfigurableDataHandler configurableDataHandler = (ConfigurableDataHandler) dataHandler;
        contentTransferEncoding = configurableDataHandler.getTransferEncoding();
    }
    if (log.isDebugEnabled()) {
        log.debug("Create MimeBodyPart");
        log.debug("  Content-ID = " + contentID);
        log.debug("  Content-Type = " + contentType);
        log.debug("  Content-Transfer-Encoding = " + contentTransferEncoding);
    }
    boolean useCTEBase64 = omOutputFormat != null && Boolean.TRUE.equals(omOutputFormat.getProperty(OMOutputFormat.USE_CTE_BASE64_FOR_NON_TEXTUAL_ATTACHMENTS));
    if (useCTEBase64) {
        if (!CommonUtils.isTextualPart(contentType) && "binary".equals(contentTransferEncoding)) {
            if (log.isDebugEnabled()) {
                log.debug(" changing Content-Transfer-Encoding from " + contentTransferEncoding + " to base-64");
            }
            contentTransferEncoding = "base64";
        }
    }
    // Now create the mimeBodyPart for the datahandler and add the appropriate content headers
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setDataHandler(dataHandler);
    mimeBodyPart.addHeader("Content-ID", "<" + contentID + ">");
    mimeBodyPart.addHeader("Content-Type", contentType);
    mimeBodyPart.addHeader("Content-Transfer-Encoding", contentTransferEncoding);
    return mimeBodyPart;
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) ConfigurableDataHandler(org.apache.axiom.attachments.ConfigurableDataHandler)

Example 74 with MimeBodyPart

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

the class AttachmentsTest method testTurkishLocale.

private void testTurkishLocale(String contentIDHeaderName) throws Exception {
    Locale locale = Locale.getDefault();
    Locale.setDefault(new Locale("tr", "TR"));
    try {
        MimeMessage message = new MimeMessage((Session) null);
        MimeMultipart mp = new MimeMultipart("related");
        MimeBodyPart bp1 = new MimeBodyPart();
        bp1.setText("<root/>", "utf-8", "xml");
        bp1.addHeader("Content-Transfer-Encoding", "binary");
        mp.addBodyPart(bp1);
        MimeBodyPart bp2 = new MimeBodyPart();
        byte[] content = new byte[8192];
        new Random().nextBytes(content);
        bp2.setDataHandler(new DataHandler("Test", "text/plain"));
        bp2.addHeader("Content-Transfer-Encoding", "binary");
        bp2.addHeader(contentIDHeaderName, "part@apache.org");
        mp.addBodyPart(bp2);
        message.setContent(mp);
        message.saveChanges();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        mp.writeTo(baos);
        String contentType = message.getContentType();
        InputStream in = new ByteArrayInputStream(baos.toByteArray());
        Attachments attachments = new Attachments(in, contentType);
        assertNotNull(attachments.getDataHandler("part@apache.org"));
    } finally {
        Locale.setDefault(locale);
    }
}
Also used : Locale(java.util.Locale) Random(java.util.Random) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) PipedInputStream(java.io.PipedInputStream) ExceptionInputStream(org.apache.axiom.testutils.io.ExceptionInputStream) InputStream(java.io.InputStream) DataHandler(javax.activation.DataHandler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 75 with MimeBodyPart

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

the class AttachmentsTest method testGetRootPartContentID.

private void testGetRootPartContentID(String contentTypeStartParam, String contentId) throws Exception {
    MimeMessage message = new MimeMessage((Session) null);
    MimeMultipart mp = new MimeMultipart("related");
    MimeBodyPart rootPart = new MimeBodyPart();
    rootPart.setText("<root/>", "utf-8", "xml");
    rootPart.addHeader("Content-Transfer-Encoding", "binary");
    rootPart.addHeader("Content-ID", "<" + contentId + ">");
    mp.addBodyPart(rootPart);
    message.setContent(mp);
    message.saveChanges();
    MemoryBlob blob = Blobs.createMemoryBlob();
    OutputStream out = blob.getOutputStream();
    mp.writeTo(out);
    out.close();
    Attachments attachments = new Attachments(blob.getInputStream(), new ContentType(message.getContentType()).toBuilder().setParameter("start", contentTypeStartParam).build().toString());
    assertEquals("Did not obtain correct content ID", contentId, attachments.getRootPartContentID());
}
Also used : ContentType(org.apache.axiom.mime.ContentType) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MemoryBlob(org.apache.axiom.blob.MemoryBlob) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) PipedOutputStream(java.io.PipedOutputStream) NullOutputStream(org.apache.commons.io.output.NullOutputStream) MimeBodyPart(javax.mail.internet.MimeBodyPart)

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