Search in sources :

Example 81 with Multipart

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

the class MessageServiceImplService method sendMessage.

@Override
public /**
     * Converts an incoming WS request into an email message and sends it to the configured 
     * email server
     */
SendResponseType sendMessage(EmailType body) {
    if (log.isDebugEnabled())
        log.debug("Enter");
    SendResponseType response = new SendResponseType();
    checkAuth(response);
    if (response.getError() == null) {
        log.info("Auth success");
        Multipart mailBody;
        MimeBodyPart mainBody;
        MimeBodyPart mimeAttach;
        String fromaddress = body.getHead().getFrom().getAddress();
        log.info("Got FROM address");
        try {
            InternetAddress addressFrom;
            addressFrom = new InternetAddress(fromaddress.toString());
            if (log.isDebugEnabled())
                log.debug("Sender: " + addressFrom);
            InternetAddress[] addressTo = new InternetAddress[1];
            int i = 0;
            for (AddressType recipient : body.getHead().getTo()) {
                addressTo[i] = new InternetAddress(recipient.getAddress());
                if (log.isDebugEnabled())
                    log.debug("Recipient: " + addressTo[i]);
                i++;
            }
            Session session = Session.getInstance(smtpProps, new SMTPAuthenticator());
            // Build message object
            MimeMessage mimeMsg = new MimeMessage(session);
            mimeMsg.setFrom(addressFrom);
            mimeMsg.setRecipients(Message.RecipientType.TO, addressTo);
            if (body.getHead().getSubject() != null) {
                mimeMsg.setSubject(body.getHead().getSubject());
            } else {
                mimeMsg.setSubject("Direct message");
            }
            mailBody = new MimeMultipart();
            mainBody = new MimeBodyPart();
            if (body.getBody().getText() != null) {
                mainBody.setText(body.getBody().getText());
            } else {
                mainBody.setText("");
            }
            mailBody.addBodyPart(mainBody);
            copyAttachments(body, mailBody);
            mimeMsg.setContent(mailBody);
            DirectMimeMessage dMsg = new DirectMimeMessage(mimeMsg, getSenderHost());
            dMsg.updateMessageID();
            Transport transport;
            if (getUseTLSforSMTP().equals("SOCKET")) {
                transport = session.getTransport("smtps");
            } else {
                transport = session.getTransport("smtp");
            }
            transport.connect();
            try {
                transport.sendMessage(dMsg, addressTo);
                // Transport.send(dMsg);
                response.setMessageID(dMsg.getMessageID());
                transport.close();
            } finally {
                transport.close();
            }
        } catch (AddressException e) {
            ErrorType et = new ErrorType();
            et.setCode(ErrorCodeType.ADDRESSING);
            et.setMessage(e.getMessage());
            response.setError(et);
            log.error(e);
        } catch (MessagingException e) {
            ErrorType et = new ErrorType();
            et.setCode(ErrorCodeType.MESSAGING);
            et.setMessage(e.getMessage());
            response.setError(et);
            log.error(e);
        } catch (Exception e) {
            ErrorType et = new ErrorType();
            et.setCode(ErrorCodeType.SYSTEM);
            et.setMessage(e.getMessage());
            response.setError(et);
            log.error(e);
            e.printStackTrace();
        }
    }
    return response;
}
Also used : Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) InternetAddress(javax.mail.internet.InternetAddress) MessagingException(javax.mail.MessagingException) SendResponseType(org.nhindirect.schema.edge.ws.SendResponseType) MessagingException(javax.mail.MessagingException) AddressException(javax.mail.internet.AddressException) InvalidPropertyException(org.springframework.beans.InvalidPropertyException) IOException(java.io.IOException) ErrorType(org.nhindirect.schema.edge.ws.ErrorType) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) AddressException(javax.mail.internet.AddressException) MimeBodyPart(javax.mail.internet.MimeBodyPart) AddressType(org.nhindirect.schema.edge.ws.AddressType) Transport(javax.mail.Transport) Session(javax.mail.Session)

Example 82 with Multipart

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

the class MimeMessageConsumeTest method populateMimeMessageBody.

/**
     * Lets encode a multipart mime message
     */
protected void populateMimeMessageBody(MimeMessage message) throws MessagingException {
    MimeBodyPart plainPart = new MimeBodyPart();
    plainPart.setText(body);
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setText("<html><body>" + body + "</body></html>");
    Multipart alt = new MimeMultipart("alternative");
    alt.addBodyPart(plainPart);
    alt.addBodyPart(htmlPart);
    Multipart mixed = new MimeMultipart("mixed");
    MimeBodyPart wrap = new MimeBodyPart();
    wrap.setContent(alt);
    mixed.addBodyPart(wrap);
    mixed.addBodyPart(plainPart);
    mixed.addBodyPart(htmlPart);
    DataSource ds;
    try {
        File f = new File(getClass().getResource("/log4j2.properties").toURI());
        ds = new FileDataSource(f);
    } catch (URISyntaxException ex) {
        ds = new URLDataSource(getClass().getResource("/log4j2.properties"));
    }
    DataHandler dh = new DataHandler(ds);
    BodyPart attachmentBodyPart;
    // Create another body part
    attachmentBodyPart = new MimeBodyPart();
    // Set the data handler to the attachment
    attachmentBodyPart.setDataHandler(dh);
    // Set the filename
    attachmentBodyPart.setFileName(dh.getName());
    // Set Disposition
    attachmentBodyPart.setDisposition(Part.ATTACHMENT);
    mixed.addBodyPart(plainPart);
    mixed.addBodyPart(htmlPart);
    // Add attachmentBodyPart to multipart
    mixed.addBodyPart(attachmentBodyPart);
    message.setContent(mixed);
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) URLDataSource(javax.activation.URLDataSource) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) URISyntaxException(java.net.URISyntaxException) DataHandler(javax.activation.DataHandler) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File) FileDataSource(javax.activation.FileDataSource) URLDataSource(javax.activation.URLDataSource) DataSource(javax.activation.DataSource)

Example 83 with Multipart

use of javax.mail.Multipart in project adempiere by adempiere.

the class EMail method setContent.

//	addAttachment
/**
	 *	Set the message content
	 * 	@throws MessagingException
	 * 	@throws IOException
	 */
private void setContent() throws MessagingException, IOException {
    //	Local Character Set
    String charSetName = Ini.getCharset().name();
    if (charSetName == null || charSetName.length() == 0)
        // WebEnv.ENCODING - alternative iso-8859-1
        charSetName = "iso-8859-1";
    //
    m_msg.setSubject(getSubject(), charSetName);
    //	Simple Message
    if (m_attachments == null || m_attachments.size() == 0) {
        if (m_messageHTML == null || m_messageHTML.length() == 0)
            m_msg.setText(getMessageCRLF(), charSetName);
        else
            m_msg.setDataHandler(new DataHandler(new ByteArrayDataSource(m_messageHTML, charSetName, "text/html")));
        //
        log.fine("(simple) " + getSubject());
    } else //	Multi part message	***************************************
    {
        //	First Part - Message
        MimeBodyPart mbp_1 = new MimeBodyPart();
        mbp_1.setText("");
        if (m_messageHTML == null || m_messageHTML.length() == 0)
            mbp_1.setText(getMessageCRLF(), charSetName);
        else
            mbp_1.setDataHandler(new DataHandler(new ByteArrayDataSource(m_messageHTML, charSetName, "text/html")));
        // Create Multipart and its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp_1);
        log.fine("(multi) " + getSubject() + " - " + mbp_1);
        //	for all attachments
        for (int i = 0; i < m_attachments.size(); i++) {
            Object attachment = m_attachments.get(i);
            DataSource ds = null;
            if (attachment instanceof File) {
                File file = (File) attachment;
                if (file.exists())
                    ds = new FileDataSource(file);
                else {
                    log.log(Level.WARNING, "File does not exist: " + file);
                    continue;
                }
            } else if (attachment instanceof URI) {
                URI url = (URI) attachment;
                ds = new URLDataSource(url.toURL());
            } else if (attachment instanceof DataSource)
                ds = (DataSource) attachment;
            else {
                log.log(Level.WARNING, "Attachement type unknown: " + attachment);
                continue;
            }
            //	Attachment Part
            MimeBodyPart mbp_2 = new MimeBodyPart();
            mbp_2.setDataHandler(new DataHandler(ds));
            mbp_2.setFileName(ds.getName());
            log.fine("Added Attachment " + ds.getName() + " - " + mbp_2);
            mp.addBodyPart(mbp_2);
        }
        //	Add to Message
        m_msg.setContent(mp);
    }
//	multi=part
}
Also used : Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) URLDataSource(javax.activation.URLDataSource) DataHandler(javax.activation.DataHandler) URI(java.net.URI) FileDataSource(javax.activation.FileDataSource) URLDataSource(javax.activation.URLDataSource) DataSource(javax.activation.DataSource) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File)

Example 84 with Multipart

use of javax.mail.Multipart in project adempiere by adempiere.

the class RequestEMailProcessor method dumpBody.

//	printEnvelope
/**
	 * 	Print Body
	 *	@param p
	 *	@throws Exception
	 */
private void dumpBody(Part p) throws Exception {
    //	http://www.iana.org/assignments/media-types/
    printOut("=================================================================");
    printOut("CONTENT-TYPE: " + p.getContentType());
    /**
		 * Using isMimeType to determine the content type avoids
		 * fetching the actual content data until we need it.
		 */
    if (p.isMimeType("text/plain")) {
        printOut("Plain text ---------------------------");
        printOut((String) p.getContent());
    } else if (p.getContentType().toUpperCase().startsWith("TEXT")) {
        printOut("Other text ---------------------------");
        printOut((String) p.getContent());
    } else if (p.isMimeType("multipart/*")) {
        printOut("Multipart ---------------------------");
        Multipart mp = (Multipart) p.getContent();
        int count = mp.getCount();
        for (int i = 0; i < count; i++) dumpBody(mp.getBodyPart(i));
    } else if (p.isMimeType("message/rfc822")) {
        printOut("Nested ---------------------------");
        dumpBody((Part) p.getContent());
    } else {
        /*
			 * If we actually want to see the data, and it's not a
			 * MIME type we know, fetch it and check its Java type.
			 */
        Object o = p.getContent();
        if (o instanceof String) {
            printOut("This is a string ---------------------------");
            printOut((String) o);
        } else if (o instanceof InputStream) {
            printOut("This is just an input stream ---------------------------");
        // TODO: process attachment
        // InputStream is = (InputStream)o;
        // int c;
        // while ((c = is.read()) != -1)
        // System.out.write(c);  // must be log. ??
        } else {
            printOut("This is an unknown type ---------------------------");
            printOut(o.toString());
        }
    }
    printOut("=================================================================");
}
Also used : Multipart(javax.mail.Multipart) Part(javax.mail.Part) InputStream(java.io.InputStream)

Example 85 with Multipart

use of javax.mail.Multipart in project adempiere by adempiere.

the class RequestEMailProcessor method getMessage.

//	getSubject
/**
	 * 	Get Message
	 *	@param msg Message
	 *	@return message or ""
	 */
private String getMessage(Part msg) {
    StringBuffer sb = new StringBuffer();
    try {
        //	Text
        if (msg.isMimeType("text/plain")) {
            sb.append(msg.getContent());
        } else //	Other Text (e.g. html/xml) 
        if (msg.isMimeType("text/*")) {
            sb.append(msg.getContent());
        } else //	Nested
        if (msg.isMimeType("message/rfc822")) {
            sb.append(msg.getContent());
        } else //	Multi Part Alternative
        if (msg.isMimeType("multipart/alternative")) {
            String plainText = null;
            String otherStuff = null;
            //
            Multipart mp = (Multipart) msg.getContent();
            int count = mp.getCount();
            for (int i = 0; i < count; i++) {
                Part part = mp.getBodyPart(i);
                Object content = part.getContent();
                if (content == null || content.toString().trim().length() == 0)
                    continue;
                if (part.isMimeType("text/plain"))
                    plainText = content.toString();
                else
                    otherStuff = content.toString();
            }
            if (plainText != null)
                sb.append(plainText);
            else if (otherStuff != null)
                sb.append(otherStuff);
        } else //	Multi Part
        if (msg.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) msg.getContent();
            int count = mp.getCount();
            for (int i = 0; i < count; i++) {
                String str = getMessage(mp.getBodyPart(i));
                if (str.length() > 0) {
                    if (sb.length() > 0)
                        sb.append("\n-----\n");
                    sb.append(str);
                }
            }
        } else {
            /*
				 * If we actually want to see the data, and it's not a
				 * MIME type we know, fetch it and check its Java type.
				 */
            Object o = msg.getContent();
            if (o instanceof String) {
                sb.append(o);
            }
        }
    } catch (Exception e) {
        log.log(Level.SEVERE, "getMessage", e);
    }
    return sb.toString().trim();
}
Also used : Multipart(javax.mail.Multipart) Part(javax.mail.Part) MessagingException(javax.mail.MessagingException) SQLException(java.sql.SQLException) IOException(java.io.IOException)

Aggregations

Multipart (javax.mail.Multipart)148 MimeMultipart (javax.mail.internet.MimeMultipart)107 MimeBodyPart (javax.mail.internet.MimeBodyPart)92 MimeMessage (javax.mail.internet.MimeMessage)82 BodyPart (javax.mail.BodyPart)62 InternetAddress (javax.mail.internet.InternetAddress)61 MessagingException (javax.mail.MessagingException)58 Session (javax.mail.Session)44 DataHandler (javax.activation.DataHandler)42 IOException (java.io.IOException)37 Properties (java.util.Properties)37 Date (java.util.Date)30 Message (javax.mail.Message)30 FileDataSource (javax.activation.FileDataSource)27 DataSource (javax.activation.DataSource)24 InputStream (java.io.InputStream)23 File (java.io.File)21 Part (javax.mail.Part)21 Test (org.junit.Test)16 UnsupportedEncodingException (java.io.UnsupportedEncodingException)11